/*
 * 
 */
package com.lge.clock.alarmclock;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
  
import android.app.Activity;
//import android.app.ActivityManagerNative;
import android.app.AlertDialog;
//import android.app.IActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetFileDescriptor;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.LGSensor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import static android.media.AudioManager.MODE_IN_CALL;
import static android.media.AudioManager.RINGER_MODE_NORMAL;
import static android.media.AudioManager.RINGER_MODE_SILENT;
import static android.media.AudioManager.RINGER_MODE_VIBRATE;
import android.media.MediaPlayer;
// [suhyun99.kim][1433] 2011.10.13
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;

import android.os.SystemProperties;//20120408 lu.dai change for U0 TD3562

import android.os.Message;

import android.os.Vibrator;
import android.provider.MediaStore;
import android.provider.Settings;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.format.DateFormat;

import android.view.KeyEvent;
import android.view.LayoutInflater;

import android.view.View;
import android.view.WindowManager;

import android.widget.ImageView;

import android.widget.TextView;
import android.widget.Toast;

import com.lge.clock.AlarmClockActivity;
import com.lge.clock.R;
import com.lge.clock.TimerFragment;
import com.lge.clock.alarmclock.StopSnoozeButton.SnoozeListener;
import com.lge.clock.alarmclock.StopSnoozeButton.StopListener;
import com.lge.clock.alarmclock.adapter.WeatherInfo;

import com.lge.clock.timer.Timers;
import com.lge.clock.util.CommonUtil;
import com.lge.clock.util.CommonUtil.AlarmDBQueryCondition;
import com.lge.clock.util.CommonUtil.COUNTRY;
import com.lge.clock.util.CommonUtil.CallStateHolder;
import com.lge.clock.util.CommonUtil.OPERATOR;
import com.lge.clock.util.CommonUtil.PrefreParent;
import com.lge.clock.util.Log;
import com.lge.clock.util.MediaInfoHolder;
import com.lge.clock.util.MediaInfoHolder.MediaLocation;

//ANDY_PORTING LGDRM [lg-drm@lge.com 100414]
import com.lge.lgdrm.Drm;
import com.lge.lgdrm.DrmContentSession;
import com.lge.lgdrm.DrmManager;
//ANDY_END

//LGE_S next. dongkyu31.lee
//import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.drm.DrmManagerClient;
import android.os.SystemProperties;
import android.content.IContentProvider;
import android.os.RemoteException;

//LGE_E nexti. dongkyu31.lee

/* LGSI_CHANGE_S : AlarmClock
 * 2012-03-26, saurabh.khare@lge.com, 
 * Numbers are changed in to arabic format in alarm clock module
*/
import java.util.Locale;
/* LGSI_CHANGE_E : AlarmClock */

import static com.lge.clock.util.CommonUtil.getDefaultRingToneInfo;
import static com.lge.clock.util.CommonUtil.getMediaInfo;

/**
 * alarm activity
 * @author donggeun.kim
 *
 */ 
public class AlarmAlert extends Activity implements SnoozeListener, StopListener, VibrateType , AlarmConstants {
	private static final String TAG = "AlarmAlert";
	
	private GridPuzzle mGridpuzzle;
	private StopSnoozeButton mStopSnoozeButton;
    private static final int KEYCODE_3DCAMERA = 92;
    private int mId;
    private int mSnooze;
    private long mTime;
    private String mMemo;
    private String mstrPuzzle;
    private String mTone;
    private String mVib;
    private String mGubun;
    private String mStrNetState;
    private ContentResolver mResolver;
    private boolean mbPuzzle = false;
    ///////////////////////////////////////
    private static final String M12 = "h:mm";
	private static final String M24 = "kk:mm";
	 
	private Calendar mCalendar;
	private String mFormat;
	private TextView dateString;//, AMText, PMText;
	/**
	 * Field mSavings.
	 */
	private static final Vector mSavings = new Vector(100);
	/**
	 * Field mAlarmSavings.
	 */
	public static final Map mAlarmSavings = new HashMap<String, AlarmAlert>();
	private String stopFlag;
    private String sideButtons;
    private static boolean mSnoozeChecker = true;

    private String mCity = "";
	private String mLocation = "";
	private String mUnit = "";
	private String mStrHighTemp;
	private String mStrLowTemp;
	private int    mWeatherIcon = -1;
	private TextView mNetwork_state;
	private static final int MSG_WEATHER = 1;
	private static final float HDPI  = 1.5f;
	private static final float XHDPI = 2.0f;
	private static final int DEF_SIZE = 16;
	
	private StringBuffer mServiceSendings = new StringBuffer(DEF_SIZE);
	
//	private boolean koreaYN = false;
	
	private String temp_TONE   = "";
    private String temp_VIB    = "";
    private String temp_MEMO   = "";
    private String temp_PUZZLE = "";
    
/* I3.0 Code [START] */
    private boolean mIsUseVolumeControl = false;
	private String mAlarmVolume;
	private String temp_ALARMVOLUME= "";
    private int resetVolume;
    
	//sugeun.hwang 2012.05.08 [7050] start
	private int sound_id = 0;
	private int sound_id_check = 0;
	//sugeun.hwang 2012.05.08 [7050] end
	
/* I3.0 Code [END] */
	
    //LGE_S. Docomo. nexti. dongkyu31.lee for playready ringtone. 
    private Build mBuild = new Build();
    private String mDevice = "l_dcm";
    private Uri mUri;
    private static DrmManagerClient mDrmManagerClient = null;
    // components of DrmStore. ex) DrmStore.RightsStatus.RIGHTS_VALID
    private final int RIGHTS_VALID = 0;
    private final int RIGHTS_INVALID =1;
    private final int RIGHTS_EXPIRED = 2;
    private final int RIGHTS_NOT_ACQUIRED = 3;
    private static final String DEFAULT_ALARM_PATH = "/system/media/audio/alarms/"+SystemProperties.get("ro.config.alarm_alert"); //Check Default Path for Stream Type

//LGE_E. Docomo. nexti. dongkyu31.lee.
    /////// Sensor object
	//hjcheong@lge.com block comment//
//	private SensorManager mSensorManager;
//	private Sensor mFlip;           
//	private SensorEventListener mSensorEventListener;
	//hjcheong@lge.com block comment//
	
	/////// incomming
	private TelephonyManager mTelephonyManager;
	
    private CallStateHolder mInitialCallState;
    
    private AudioManager mAudioManager = null;
    private static final String PREFERENCES = "com.lge.clock_preferences";
    
    //public static final float FLIP_UPSIDE_DOWN = 1.0f;
    //public static final float FLIP_DOWNSIDE_UP = 2.0f;
    private static boolean mDIALOG_CHECKED; 
    //private Context mContexts;
    private String mPuzzleSetting_Value = null;
    
    private boolean mPlayingMusic = false;
    
    private SensorManager mSensorManager;
//    private Sensor mSensor;
    private SensorEventListener mSensorEventListener;
//    private LgeSensor mLgeSensor;
    
    private ImageView mAlarmIcon;
    private AnimationDrawable mAnimation;
    
//    private String gestureAlarm = "";
    private boolean mPouch = false;
    private long mAutoSnoozeStartTime = 0L;
	private boolean find_alarm_tone = false; //voice recode bug
    
    static int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
    
    /**
     * during it is incomming, when alarm is happend, go to snooze
     */
    private final PhoneStateListener mPhoneStateListener = new PhoneStateListener() 
    {
        @Override
        public void onCallStateChanged(int state, String ignored) 
        {
        	if (state != TelephonyManager.CALL_STATE_IDLE && mInitialCallState.equals(CommonUtil.getNowCallState(getApplicationContext(), mTelephonyManager))== false) {
        		soundAndVibratorCancel(mId);       		 
        		
	            if (mSnooze > 0) {
	            	mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_SNOOZE,  mId));         
	            	return;
	            }
	            else if (mSnooze == 0) {
	            	//TD#89568 : Fixed not to auto-snooze if snooze duration is off.
	            	mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_AUTOSTOP,  mId));   
	            	/*
	            	ContentValues value = new ContentValues();
		        	mSnooze = 5;
		        	value.put("snooze", 5);
		        	mResolver.update(ALProvider.CONTENT_ALARMS_URI, value, "_id=" + mId, null);
	            	mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_SNOOZE,  mId));
	            	*/
	            	return ;	
	            }
            }
        }     
    };
    
    /**
     * 2012.03.26 suein1209.kim
     * get side button default value
     */
    private String getSideButtonDefaultValue(){
    	if(CommonUtil.isSprintOperator()){
    		/*if sprint operator*/
    		return "3";//Silence
    		
    	}else{
    		/*if common operator*/
    		return "1";//Snooze
    		
    	} //End Of fi
    } //End Of Method getSideButtonDefaultValue

    
    /**
     * Method onCreate.
     * @param icicle Bundle
     */
    @Override                            
    protected void onCreate(Bundle icicle) 
    {
    	super.onCreate(icicle);
    	mIsUseVolumeControl = CommonUtil.isUseVolumeControl();
        AlarmAlertWakeLock.acquireCpuWakeLock(this);
        
        /**
         * when music is playing, music is stopped by intent
         * changed by essin@lge.com 2010.12.07
         */
		
        //[yeonju7.kim][p2][2011.08.30] alarmalert Intent
        Intent alarmAlert = new Intent("com.lge.clock.alarmclock.ALARM_ALERT");
        sendBroadcast(alarmAlert);
        
        Intent closeDialogs = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
		sendBroadcast(closeDialogs);

		mAutoSnoozeStartTime = System.currentTimeMillis();		
        // 20101119_mhkwon_SU660_QM_Music_pause_play [[
		
//		Log.d(TAG,"AlarmAlert onCreate sendBroadcast [Play Pause]");
//	    Intent music = new Intent("com.android.music.musicservicecommand");
//	    music.putExtra("command", "toggleplay");
//	    music.putExtra("status", "start");
//	    sendBroadcast(music);
	    
	    // [start][yeonju7.kim][P940] 2011.09.21 ADD Fm Radio intent "status"  
//        Log.d(TAG, "AlarmAlert onCreate sendBroadCast [FmRadio pause]");
//        Intent fmRadio = new Intent("com.ti.server.fmresumecmd");
//        fmRadio.putExtra("status", "start");
//        sendBroadcast(fmRadio);
        // [end][yeonju7.kim][P940] 2011.09.21 ADD Fm Radio intent "status"  
        
        // 20101119_mhkwon_SU660_QM_Music_pause_play 
        mTelephonyManager =	(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        mInitialCallState = CommonUtil.getNowCallState(getApplicationContext(), mTelephonyManager);
        
        mDIALOG_CHECKED = true;
        /////////////////////////////////////////////////////////////////////////////////////
    	// [3D_GESTURE_APP] [START_LGE]
        
        //hjcheong@lge.com block comment//
//        mSensorManager =(SensorManager)getSystemService(Context.SENSOR_SERVICE);
//		mFlip = mSensorManager.getDefaultSensor(Sensor.TYPE_SENSOR_LGE_GESTURE_FLIP);
//		mSensorEventListener = new SensorEventListenerImpl();
        
        //hjcheong@lge.com block comment//
		// [3D_GESTURE_APP] [END_LGE]
//        mLgeSensor = new LgeSensor();      
		/////////////////////////////////////////////////////////////////////////////////////
		// [side button setting]      
		SharedPreferences prefs = this.getSharedPreferences(PREFERENCES, 0);
		/*[START] 2012.04.04 suein1209.kim add side button in sprint model*/
//		sideButtons  = prefs.getString("volume_button_setting", "1");
        sideButtons  = prefs.getString("volume_button_setting", getSideButtonDefaultValue());
        /*[END] 2012.04.04 suein1209.kim add side button in sprint model*/
        Log.d(TAG, "===sideButtons====>" + sideButtons );
        //mContexts  =	this;
        /////////////////////////////////////////////////
        Intent i   =	getIntent();
        mId   	   =	i.getIntExtra("id", 0);
        Log.d(TAG, " ==[onCreate]==== ID ====> " + mId );
             
        mSnooze    =	i.getIntExtra("snooze", 0);    
        mMemo	   =	i.getStringExtra("memo");  
        mstrPuzzle =	i.getStringExtra("puzzle");
        mTone	   =	i.getStringExtra("tone");  	
        mVib	   =	i.getStringExtra("vib");   
        mTime	   =	i.getLongExtra("time", 0l);  
        stopFlag   =	i.getStringExtra("stop");
        mGubun	   =	i.getStringExtra("gubun");

/* I3.0 Code [START] */
        if(mIsUseVolumeControl){
        	mAlarmVolume = i.getStringExtra(AlarmMeta.COLUMNS.ALARM_VOLUME);
        	Log.i(TAG,"mAlarmVolume = " + mAlarmVolume);
        }
/* I3.0 Code [END] */
        
        try {
        	mResolver =	getContentResolver();
        	mAlarmSavings.put(Integer.toString(mId), this);
        } catch ( NullPointerException e ) {
        	e.printStackTrace();
        }
        
        if ( mstrPuzzle != null && mstrPuzzle.equals("On") ){ //WBT#47794 fixed by mo2sangbong.lee@lge.com 2011.07.22 added null check
        	mbPuzzle = true;
        	
        	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        
        mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
		if("Off".equalsIgnoreCase(mTone) == false && silenceModeChecking() == false ) {
	        mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
		}else{
			mAudioManager = null;
		}
		
        ///////////////////////////////////////////////////////////
        /**
         * alarm play to 1 min
         */
        
        if(AlarmClockActivity.mShutDown == true){
        	soundAndVibratorCancel(mId);
        	mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_STOP,  mId));
        }else{
        	alarmPlaying(mId);
        	
        	/**
             *  multicheck (alarm snooze)
             */
            multiCheck(mId, mTime, false);     
                                               
            /**
             *  [next alarm] time output
             */    
            Log.d(TAG, " -- setNextAlert ---in Alarm fire screen~ !!!");
            Alarms.setNextAlert(this);
            
            // When event occurs during sleep mode, unlock the screen
            requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
  //          		| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                    | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
            
            updateLayout();
        	
        }
    }
    
    private View mView = null;
    /**
     *  screen layout setting
     */
    private void updateLayout() {

    	if(mView == null){
	        LayoutInflater inflater = LayoutInflater.from(this);
	        mView = inflateView(inflater);	   
    	}
    	setContentView(mView);

        // [minjoong.park][1398] 2011.10.15. START
    // [taewan.kim][1830] 2011.11.15. START
        mStopSnoozeButton = (StopSnoozeButton) findViewById(R.id.bb);
        mStopSnoozeButton.setStopListener(this);
        mStopSnoozeButton.setSnoozeListener(this);
        if (!mPouch) {
   	// [taewan.kim][1830] 2011.11.15. END
            if (mbPuzzle) {
                mGridpuzzle = (GridPuzzle) findViewById(R.id.grid);
                mGridpuzzle.setStopGridListener(this);

                mStopSnoozeButton.setPuzzleOn(true); // hide stop button
                SharedPreferences pref = getSharedPreferences(PREFERENCES, 0);
                mPuzzleSetting_Value = pref.getString("puzzle_setting", "0");

                TextView mTap = (TextView) findViewById(R.id.number_tap);
                if ("0".equals(mPuzzleSetting_Value)) 
                    mTap.setText(R.string.sp_tabNumerOrder_NORMAL);
                else if ("1".equals(mPuzzleSetting_Value)) 
                    mTap.setText(R.string.sp_tabAlphabetOrder_NORMAL);
                //[mo2sangbong.lee][2019] 2011.11.29 START
                else if ("2".equals(mPuzzleSetting_Value)) 
                    mTap.setText(R.string.sp_tabKoreanOrder_NORMAL);
                //[mo2sangbong.lee][2019] 2011.11.29 END
            } else {
                mAlarmIcon = (ImageView) findViewById(R.id.alarmIcon);

                mNetwork_state = (TextView) findViewById(R.id.network_error);
                // mNetwork_state.setVisibility(View.GONE);

                mStopSnoozeButton.setPuzzleOn(false); // show stop button

            }

            time_init();

            /* Set the title from the passed in label */
            TextView title = (TextView) findViewById(R.id.alertTitle);
            title.setText(mMemo);
            title.setSelected(true);

            // setFont("/system/fonts/DroidSans.ttf");
        }
        // [minjoong.park][1398] 2011.10.15. END
       mAlarmIcon = (ImageView)findViewById(R.id.alarmIcon);
        
       time_init();
    }
    
    /**
     * Method inflateView.
     * @param inflater LayoutInflater
     * @return View
     */
    protected View inflateView(LayoutInflater inflater) 
    {
        // [minjoong.park][1398] 2011.10.15. START
    	// [taewan.kim][1830] 2011.11.15. START
    	if(mPouch){
    		return inflater.inflate(R.layout.alarm_alert_pouch, null);
    	}else{
    		if( mbPuzzle ) {
        		return inflater.inflate(R.layout.alarm_alert_puzzle, null);
        	}
        	else {
        		return inflater.inflate(R.layout.alarm_alert_weather, null);
        	}
    	}
    	// [minjoong.park][1398] 2011.10.15. END
    } 
     
    
    /**
     *  time output on the screen
     * 
     */
    // alarm screen update every 1 min.
    public void time_init() {        
        dateString = (TextView)findViewById(R.id.dateString);
        mCalendar = Calendar.getInstance();
        mFormat = is24HourMode(this) ? M24 : M12;
 
        /* monitor time ticks, time changed, timezone */
        IntentFilter filter = new IntentFilter();
//        filter.addAction(Intent.ACTION_TIME_TICK);
//        filter.addAction(Intent.ACTION_TIME_CHANGED);
        filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        filter.addAction(Timers.TIMER_ALERT_ACTION);
        registerReceiver(mIntentReceiver, filter, null, mHandler); 
        updateTime();
    }        
    
    /* called by system on minute ticks */
    private final Handler mHandler = new Handler();
    private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
    	@Override
        public void onReceive(Context context, Intent intent) {
    		
			if ( intent.getAction().equals( Intent.ACTION_TIMEZONE_CHANGED)) {
				mCalendar = Calendar.getInstance();
				updateTime();
			}
            
			//TD#16059 fixed by mo2sangbong.lee@lge.com 2011.07.23 Start
			if ( intent.getAction().equals(Timers.TIMER_ALERT_ACTION))
			{
				soundAndVibratorCancel(mId);
				autoSnoozeGoing();
			}
        }    
    };

    private void updateTime() {
    	
    	TextView apm;
    	TextView mHour01;
    	TextView mHour02;
    	TextView mMinute01;
    	TextView mMinute02;
    	
    	mCalendar.setTimeInMillis(System.currentTimeMillis());
    	int minutes = mCalendar.get(Calendar.MINUTE);
    	int hour    = mCalendar.get(Calendar.HOUR);
    	
    	String[] strMONTH = {
    	    		getResources().getString(R.string.sp_january_SHORT), 
    	    		getResources().getString(R.string.sp_February_SHORT), 
    	    		getResources().getString(R.string.sp_march_SHORT),
    	    		getResources().getString(R.string.sp_april_SHORT),
    	    		getResources().getString(R.string.sp_may_SHORT),
    	    		getResources().getString(R.string.sp_june_SHORT),
    	    		getResources().getString(R.string.sp_july_SHORT),
    	    		getResources().getString(R.string.sp_august_SHORT),
    	    		getResources().getString(R.string.sp_september_SHORT),
    	    		getResources().getString(R.string.sp_october_SHORT),
    	    		getResources().getString(R.string.sp_november_SHORT),
    	    		getResources().getString(R.string.sp_december_SHORT)};
    	    
    	String[] yoil = {"", 
    	    		getResources().getString(R.string.sp_sunday_NORMAL),
    	    		getResources().getString(R.string.sp_monday_NORMAL),
    	    		getResources().getString(R.string.sp_tuesday_NORMAL),
    	    		getResources().getString(R.string.sp_wednesday_NORMAL),
    	    		getResources().getString(R.string.sp_thursday_NORMAL),
    	    		getResources().getString(R.string.sp_friday_NORMAL),
    	    		getResources().getString(R.string.sp_saturday_NORMAL)};
    	
    	boolean is24HourFormat = DateFormat.is24HourFormat(this) ;  
    	Log.d(TAG, "===updateTime===> " +  hour + " / " + minutes) ;          		
        //////////////////////////////////////////////////////////////////////////////
        if (is24HourFormat == true) {
			Log.d(TAG, "==========24 mode==============") ;
			
			findViewById(R.id.apm_ID).setVisibility(View.INVISIBLE);
			findViewById(R.id.hour_Text01).setPadding(0, 0, 0, 0);
			if (mCalendar.get(Calendar.AM_PM) == 1) {
				hour += 12 ;
	        } 
		}    
                                                                     
        if (is24HourFormat == false){
        	Log.d(TAG, "==========am/pm mode==============>>> " +  mCalendar.get(Calendar.AM_PM) ) ;
    		if ( mCalendar.get(Calendar.AM_PM) == 0 ) {
    			apm = (TextView)findViewById(R.id.apm_ID);
    			apm.setText(R.string.sp_AM_string_NORMAL);
    		}
    		else {
    			apm = (TextView)findViewById(R.id.apm_ID);
    			apm.setText(R.string.sp_PM_string_NORMAL);
    		}
        	
	        if (hour == 0) {
				hour = 12;
			}
        }
                     
		int digit1 = hour / 10;
		int digit0 = hour % 10;
//		Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),
//        "fonts/Clockopia.ttf");
/* LGSI_CHANGE_S : AlarmClock
 * 2012-03-26, saurabh.khare@lge.com, 
 * Numbers are changed in to arabic format in alarm clock module
*/
//		mHour01 = (TextView)findViewById(R.id.hour_Text01);
//		mHour01.setText(mNumDigitDrawables[digit1]);
		//if (is24HourFormat == false && digit1 == 0) {
		//	mHour01.setVisibility(View.GONE);
		// }
//		mHour02 = (TextView)findViewById(R.id.hour_Text02);
//		mHour02.setText(mNumDigitDrawables[digit0]);
/* LGSI_CHANGE_E : AlarmClock */
//		mHour01.setTypeface(tf);
//		mHour02.setTypeface(tf);
           
        ////////////////////////////////////////////////////////////////////////////////////////
		
		int mdigit1 = minutes / 10;
		int mdigit0 = minutes % 10;   
/* LGSI_CHANGE_S : AlarmClock
 * 2012-03-26, saurabh.khare@lge.com, 
 * Numbers are changed in to arabic format in alarm clock module
*/
	if("ar".equals(Locale.getDefault().getLanguage()) || "fa".equals(Locale.getDefault().getLanguage())){
           	/*Based on locale we are changing the values*/
		mHour01 = (TextView)findViewById(R.id.hour_Text01);
		mHour01.setText(String.format(Locale.getDefault(),"%d", digit1));
	        if (is24HourFormat == false && digit1 == 0) {
		    mHour01.setVisibility(View.GONE);
	        }
		mHour02 = (TextView)findViewById(R.id.hour_Text02);
		mHour02.setText(String.format(Locale.getDefault(),"%d", digit0));
		mMinute01 = (TextView)findViewById(R.id.min_Text01);
		mMinute01.setText(String.format(Locale.getDefault(),"%d", mdigit1));
		mMinute02 = (TextView)findViewById(R.id.min_Text02);
		mMinute02.setText(String.format(Locale.getDefault(),"%d", mdigit0));
        }
	else {
		mHour01 = (TextView)findViewById(R.id.hour_Text01);
		mHour01.setText(mNumDigitDrawables[digit1]);
		if (is24HourFormat == false && digit1 == 0) {
			mHour01.setVisibility(View.GONE);
		}
		mHour02 = (TextView)findViewById(R.id.hour_Text02);
		mHour02.setText(mNumDigitDrawables[digit0]);
	
		
		//mHour01.setTypeface(tf);
		//mHour02.setTypeface(tf);
           
		
		mMinute01 = (TextView)findViewById(R.id.min_Text01);
		mMinute01.setText(mNumDigitDrawables[mdigit1]);
		mMinute02 = (TextView)findViewById(R.id.min_Text02);
		mMinute02.setText(mNumDigitDrawables[mdigit0]);
		}
/* LGSI_CHANGE_E : AlarmClock */
//		mMinute01.setTypeface(tf);
//		mMinute02.setTypeface(tf);
		
      /* LGSI_CHANGE_S
       2012-02-16, sarah.ganihar@lge.com, 
	   Alarm Alert Numbers(HH:MM) to be displayed in arabic
      */

		
          if(CommonUtil.isArabFarsiLanguage()){
          mHour01.setText(CommonUtil.convertArabFarsiNum(Integer.toString(digit1),false));
          mHour02.setText(CommonUtil.convertArabFarsiNum(Integer.toString(digit0),false));
          mMinute01.setText(CommonUtil.convertArabFarsiNum(Integer.toString(mdigit1),false));
          mMinute02.setText(CommonUtil.convertArabFarsiNum(Integer.toString(mdigit0),false));
      }
   /* LGSI_CHANGE_E */
	  
	
	
		
		//mMinute01.setTypeface(tf);
		//mMinute02.setTypeface(tf);
		
		//////////////////////////////////////////////////////////////////////////////////////////////

		String dateStringTemp;
		
			dateStringTemp = yoil[mCalendar.get(Calendar.DAY_OF_WEEK)] + ", " 
			+ strMONTH[mCalendar.get(Calendar.MONTH)] + " " 
			+ mCalendar.get(Calendar.DATE);

		/*[START] 2012.03.14 suein1209.kim change the display time type in Japan lang*/
        if (CommonUtil.isAsiaLanguage(this)) {
        	String dateStringkor = (mCalendar.get(Calendar.MONTH)+1) + "/" + mCalendar.get(Calendar.DATE) +  " (" + yoil[mCalendar.get(Calendar.DAY_OF_WEEK)] + ")";
        	dateString.setText(dateStringkor);
  
        }
/* LGSI_CHANGE_S : AlarmClock
 * 2012-03-26, saurabh.khare@lge.com, 
 * Numbers are changed in to arabic format in alarm clock module
*/
	else if (CommonUtil.isArabFarsiLanguage()){
/* LGSI_CHANGE_S : AlarmClock
 * 2012-04-14, srinivas.turaga@lge.com, 
 * Added / between DD & MM to fix date separator issue in alarm clock for Arabic/Farsi
 */
		dateString.setText( yoil[mCalendar.get(Calendar.DAY_OF_WEEK)] + " " + strMONTH[mCalendar.get(Calendar.MONTH)] + "/" + String.format(Locale.getDefault(),"%d", mCalendar.get(Calendar.DATE)) );
/* LGSI_CHANGE_E: AlarmClock*/
	} 
/* LGSI_CHANGE_E : AlarmClock */
	else {
        	dateString.setText( dateStringTemp );
        }
        /*[END] 2012.03.14 suein1209.kim change the display time type in Japan lang*/
    }
  
	/**
	 *  network state false
	
	 * @throws Exception */
	public void nonetwork() {
		mStrNetState = "(" +  getText(R.string.nonetwork).toString() + ")";
		mNetwork_state.setText( mStrNetState );    
		mNetwork_state.setVisibility(View.VISIBLE);
	}
	
	/**
	 * nolocation string setting
	
	 * @throws Exception */
	public void nolocation() {
		mStrNetState = "(" + getText(R.string.no_city).toString();
        mNetwork_state.setText( mStrNetState );  
        mNetwork_state.setVisibility(View.VISIBLE);
    }
	
	/**
	 * network state true, but data loading failed
	
	 * @throws Exception */
	public void noData() {
		mStrNetState = "(" +  getText(R.string.loading_error).toString() + ")";
		mNetwork_state.setText( mStrNetState );         
		mNetwork_state.setVisibility(View.VISIBLE);
	}
	
	/**
	 * weather info loading true
	 */
	private final Handler weather_handler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			switch(msg.what){
				case MSG_WEATHER:
					WeatherInfo info = (WeatherInfo)msg.obj;
					//Log.d(TAG, "123==handleMessage curThreadName == " + Thread.currentThread().getName());
					///////////////////////////////////////////////////
					
					String gubun = info.getCityName();
					if (mLocation.equalsIgnoreCase("0")) {
                        try {
                            nolocation();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return;
                    } 
					if (gubun != null && "WF_NETWORK_ERROR".equalsIgnoreCase(gubun)) {
						
						try {
							nonetwork();
						} catch (Exception e) {
							e.printStackTrace();
						}          
			        	return ;   
					}
					     
					if (gubun != null && "WF_FAIL_ERROR".equalsIgnoreCase(gubun)) {
						
						try {
							noData();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}          
			        	return ;   
					}
					               
					mStrHighTemp = info.getHighTemp();
					mStrLowTemp  = info.getLowTemp();
					
					String weatherIcon = info.getWeatherIcon();
					if ( weatherIcon == null ) {
						try {
							nonetwork();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}          
			        	return ; 
					}
					
					try {
						mWeatherIcon = Integer.parseInt(weatherIcon);
					} catch ( NumberFormatException e ) {
						e.printStackTrace();
					}
					break;
					
				default :
					break;
					
				}
		}
	};
    
    /**
     * Method onNewIntent.
     * @param tt Intent
     */
    @Override
    protected void onNewIntent(Intent tt) {
    	super.onNewIntent(tt);       
        int 	hid   	   		=	tt.getIntExtra("id", -1);
        String  hgubun	   		=	tt.getStringExtra("gubun");
        long    htime			=	tt.getLongExtra("time", 0l);
        String  multi	    	=	tt.getStringExtra("multi");
        
        Log.d(TAG, "==onNewIntent ====== ID : " + hid + " / hgubun = " + hgubun);
        Log.d(TAG,"=onNewIntent === legal====id===" + mId + "  gubun = " + mGubun+ " legal time = " + mTime);
        Log.d(TAG,"==onNewIntent == incoming id===" + hid + "  gu = " + hgubun + "  new   time = " + htime );
        
        if (mId == hid) {
        	Log.d(TAG,"====onNewIntent === same legal===" + mId);
        	return;      
        } 
                
        if ("yes".equalsIgnoreCase(multi)) {
        	Log.d(TAG,"==onNewIntent==legal same time==" +  mTime); // + mID);
        	Log.d(TAG,"==onNewIntent=== same time==" +  multi); // + mID);
        	
        	if (htime > mTime) {
        		boolean aa = multiCheck(hid, htime, true);
        		if (aa == true){
        			Log.d(TAG,"==onNewIntent=multi== [yes] === OK ==");
        			Alarms.setNextAlert(this);
        		
        		}else {
        			Log.d(TAG,"==onNewIntent=multi== [no] ====");
        		}   
        		return;
        	}                               
        	return; 
        } 
        
        if (mId != hid  &&  mTime > htime) {
        	Log.d(TAG, "===onNewIntent=== wrong time===") ;
        	return ;
        }
        
        if (mId != hid  &&  mTime == htime) {
        	Log.d(TAG,"==== onNewIntent ==== 111111111111111111111111111111");
        	for (int j=0; j < mSavings.size(); j++){
        		if (hid == ((Intent)(mSavings.elementAt(j))).getIntExtra("id", -1)){ 
        			return;      
            	}
            }
        	                                               
        	Log.d(TAG,"=== onNewIntent === in for11==add===   ID : " + hid );  
        	mSavings.add(tt) ;
    		Alarms.setNextAlert(this);
        	return;                                     
        }
        else {
        	Log.d(TAG,"==== onNewIntent 222222222222222222222222222222222");
        }

        boolean judge	=	false ; 
        for (int j=0; j < mSavings.size(); j++) {
        	if (hid == ((Intent)(mSavings.elementAt(j))).getIntExtra("id", -1) && htime == ((Intent)(mSavings.elementAt(j))).getLongExtra("time", -1) ) 
			{ 
        		judge	=	true ;
        		Log.d(TAG, "=== onNewIntent == alright 2=====");
        		break;
			}
        }
               
        boolean judge2	=	false ; 
        for (int j=0; j < mSavings.size(); j++) {
        	if (mId == ((Intent)(mSavings.elementAt(j))).getIntExtra("id", -1) && mTime == ((Intent)(mSavings.elementAt(j))).getLongExtra("time", -1) ) 
        	{ 
        		judge2	=	true ;
        		Log.d(TAG, "=== onNewIntent  alright 3=====");
        		break;
        	}
        }
          
        if (judge == false && judge2 == false) {           
	        Log.d(TAG, "=== onNewIntent in for22==add=== ID : " + hid);  
	        mSavings.add(tt) ;
	        Alarms.setNextAlert(this);
        }           
    }                   
             
    
    /**
     * suein1209.kim
     * 
     * Gesture column name
     */
    private static String TYPE_SETTING_GESTURE_FLAG = "gesture_alarm";
    
    /**
     * suein1209.kim
     * 
     * Is Check Gesture flag in Setting menu
     * @return
     */
    private boolean isSetGestureFlag(){
    	return Settings.System.getInt(getContentResolver(), TYPE_SETTING_GESTURE_FLAG, 0) == 1;
    	
    }//End Of Method isSetGestureFlag
    
    /**
     * suein1209.kim
     * 
     * init Sensor manager and register listener
     * 
     * @param mSensorEventListener
     */
    private SensorManager getInitedSensorManager(SensorEventListener mSensorEventListener){
    	
    	SensorManager retSensorMgr = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
		if ((mSensorEventListener != null)) {
			
			Sensor mSensor = retSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
			/*regi*/
			retSensorMgr.registerListener(mSensorEventListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
		} else {
			/* Do nothing */
			Log.e(TAG, "Sensor Manager Register Listener Error");
			
		}// End Of Method
		return retSensorMgr;
    } //End Of Method getInitedSensorManager
    
    /**
     * Method onResume.
     */
    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "[onResume]");
        AlarmClockActivity.mSensor = true;
        AlarmAlertWakeLock.acquireScreenWakeLock(this);
		// [minjoong.park][1398] 2011.10.15. START
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_DOCK_EVENT);
        registerReceiver(mPouchIntentReceiver, filter, null, mHandler);
        // [minjoong.park][1398] 2011.10.15. END
        
        /*[START] 2012.02.20 suein1209.kim*/
        if(isSetGestureFlag() && CommonUtil.isFacingSensorSupported(this)){
        	/*set Sensor Event Listener*/
        	mSensorEventListener = new SensorEventListenerImpl();
        	
        	/*initalize Sensor Manger*/
        	mSensorManager = getInitedSensorManager(mSensorEventListener);
        } //End Of if
        
        /*[END] 2012.01.20 suein1209.kim*/
        
        
//        mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
//		mSensor = mLgeSensor.getDefaultSensor(mSensorManager);
//		mSensorEventListener = new SensorEventListenerImpl();
//		
////		gestureAlarm =  mLgeSensor.getGestureAlarm(); 
//		
//		if(mSensorEventListener == null ) {
//			
//		}else{
//            ContentResolver resolver = getContentResolver();
////            if (gestureAlarm != null) {
//                if ((Settings.System.getInt(resolver, "gesture_alarm", 0) == 1)) {
//                    mSensorManager.registerListener(mSensorEventListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
//                    Log.e(TAG, "mSensorEventListener");
//                }
////                if ((Settings.System.getInt(resolver, gestureAlarm, 1) == 1)) {
////                    mSensorManager.registerListener(mSensorEventListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
////                    Log.e(TAG, "mSensorEventListener");
////                }
//
////            }
//		}
      //hjcheong@lge.com block comment
        // [3D_GESTURE_APP] [END_LGE]    

	// [suhyun99.kim][1433] 2011.10.13. START
	
/* I3.0 Code [START] */
        if(mIsUseVolumeControl){
			mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
			resetVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM);
			mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, Integer.parseInt(mAlarmVolume), 0);
        }
/* I3.0 Code [END] */
							
		
	// [suhyun99.kim][1433] 2011.10.13. END
    }
    
    // [minjoong.park][1398] 2011.10.15. START
    private final BroadcastReceiver mPouchIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "intent.getAction() => " + intent.getAction());
            //mPouch = PouchMode.getDockState(intent);
            boolean bPouch = PouchMode.getDockState(intent);
            
            if( bPouch != mPouch){
            	mPouch = bPouch;
            	Log.i(TAG, "mPouch " + mPouch);
            	
	            /*[START] 2012.04.30 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #157383 */
	            mView = null;
	            /*[END] 2012.04.30 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #157383 */
	            
	            updateLayout();
	            onWindowFocusChanged(true);
            }
        }
    };
    // [minjoong.park][1398] 2011.10.15. END
    
    private void releaseLocks() {
    	synchronized ( this ) {
    		AlarmAlertWakeLock.release();
		}
    }
    
    /**
     * 2012.01.31 suein1209.kim
     * External colums 
     */
    private static final String[] EXTERNAL_COLUMNS = new String[] {
	    android.provider.BaseColumns._ID,
		android.provider.MediaStore.MediaColumns.TITLE,
		"\"" + MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "\"",
		android.provider.MediaStore.Audio.AudioColumns.TITLE_KEY
	};
    
    /**
     * Method onPause.
     */
    @Override
    protected void onPause() {
		Log.d(TAG, "[onPause]");
		super.onPause();
		
		/*suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #126419 */
		/*is external media file*/
		if(mMediaPlayer != null && mMediaPlayer.isPlaying() == false){
			MediaInfoHolder mediaInfo = CommonUtil.getMediaInfo(mResolver, mTone, AlarmDBQueryCondition.SET_ALARM);
			if(mediaInfo.mediaLocation == MediaLocation.NO_WHERE){
				Log.d(TAG, "UnExpected removed SD card so, cancel the sound ("+mTone+")");
				soundCancel(mId);
			} //End Of if
		}
		
		//[mo2sangbong.lee][1817] 2011.11.11 START
		if (mPouchIntentReceiver != null) {
			try{
				unregisterReceiver(mPouchIntentReceiver);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		//[mo2sangbong.lee][1817] 2011.11.11 END
		if ((mSensorManager != null) && (mSensorEventListener != null)){
			mSensorManager.unregisterListener(mSensorEventListener);
		}
    }               
                     
    /**
     * Method onStop.
     */
    @Override
    protected void onStop() {
    	Log.d(TAG, "[onStop]");
		super.onStop();
		releaseLocks();            
		// [3D_GESTURE_APP] [START_LGE]
		//hjcheong@lge.com block comment
//		mSensorManager.unregisterListene(mSensorEventListener); // 3D Gesture
		//hjcheong@lge.com block comment
		// [3D_GESTURE_APP] [END_LGE]
		// listener
        //////////////////////////////////////////////
		
		/**
         * when music play, music stop by intent
         * added by essin@lge.com 2010.12.07
         */
		// 20101119_mhkwon_SU660_QM_Music_pause_play [[
//		Log.d(TAG,"AlarmAlert onStop sendBroadCast [Music Restart]");
//        Intent music = new Intent("com.android.music.musicservicecommand");
//        music.putExtra("command", "toggleplay");
//        music.putExtra("status", "end");
//        sendBroadcast(music);
        
        // [start][yeonju7.kim][P940] 2011.09.21 ADD Fm Radio intent "status"  
//        Log.d(TAG, "AlarmAlert onStop sendBroadCast [FmRadio Restart]");
//        Intent fmRadio = new Intent("com.ti.server.fmresumecmd");
//        fmRadio.putExtra("status", "end");
//        sendBroadcast(fmRadio);
        // [end][yeonju7.kim][P940] 2011.09.21 ADD Fm Radio intent "status"          
        
		// 20101119_mhkwon_SU660_QM_Music_pause_play 

		// [suhyun99.kim][1433] 2011.10.13. START
		if ((mAudioManager != null) && (mAudioFocusListener != null)){
			mAudioManager.abandonAudioFocus(mAudioFocusListener);
		}
		// [suhyun99.kim][1433] 2011.10.13. END
		
        if( playing == true ) 
        {
        	soundAndVibratorCancel(mId);
			
			if (mSnooze > 0) 
			{
				mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_SNOOZE,  mId));         
	         	return ;
			}
			else if (mSnooze == 0) 
			{	
				ContentValues value = new ContentValues();
	        	mSnooze = 5;
	        	value.put("snooze", 5);
	        	mResolver.update(ALProvider.CONTENT_ALARMS_URI, value, "_id=" + mId, null);
	         	mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_SNOOZE,  mId));
	         	return ; 	
	        }
		}
    }          
    
    /**
     *  to do before end.....
     */      
    private void finishReady() {       
   
    	Log.d(TAG, "============[[ onDestroy() ]]========= mSavings()" +  mSavings.size()); 
    	Log.d(TAG, "=111==before===setNextAlert================");
        Alarms.setNextAlert(this);
        Log.d(TAG, "==222=after====setNextAlert================");

		//[hyunjung78.park] 2011.08.16 when alarm alert from lock screen, send broadcast to lock screen when press stop button START
		Intent alarm_intent = new Intent();
	 	alarm_intent.setAction( "alarm.current.nextAlarm" );
	 	sendBroadcast(alarm_intent);
        //[hyunjung78.park]2011.08.16 when alarm alert from lock screen, send broadcast to lock screen when press stop button END
        
        mAlarmSavings.remove(Integer.toString(mId));
        try{
        	unregisterReceiver(mIntentReceiver);
        }catch(Exception e){
			e.printStackTrace();
		}
    	/////////////////////////////////////////////////
    	Intent kk	=	null ;       
        for (int i=0; i < mSavings.size(); i++) {
        	kk = (Intent)(mSavings.elementAt(i));
        	Log.d(TAG, "remove=ID==> " +  kk.getIntExtra("id", -1) + "  mSavings()=" + mSavings.size() ); 
        	mSavings.removeElementAt(i);
      		break;
        }     
                           
		if (kk != null) {
			this.startActivity(kk);    
		}    
    }
    
    /**
     * Method onDestroy.
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
        mTelephonyManager.listen(mPhoneStateListener, 0);
        
		finishReady();
		
		cleanupView(findViewById(R.id.alarmIcon));
		
    }
    
    // alarm activity process kill
	/**
	 * Method forceStop.
	 */
	public void forceStop() {
		Log.d(TAG, "============ force Stop =======> " + mId); //		
		soundAndVibratorCancel(mId);   		
		finish();
	}         
	  
	// alarm activity process kill related Voip
	/**
	 * Method forceStop_Related_voip.
	 */
	public void forceStop_Related_voip() {
		soundAndVibratorCancel(mId);
		Log.d(TAG, "=== mPhoneStateListener ===OK onCallStateChanged ====");
        if (mSnooze > 0) {
        	
        	mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_SNOOZE,  mId));          
        	return ;
        	
         } else if (mSnooze == 0) 
         {
        	//TD#89568 : Fixed not to auto-snooze if snooze duration is off.
        	 mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_AUTOSTOP,  mId));  
        	 
        	/*
        	ContentValues values = new ContentValues();
        	mSnooze = 5;
        	values.put("snooze", 5);
        	getContentResolver().update(ALProvider.CONTENT_ALARMS_URI, values, "_id=" + mId, null);
        	
        	mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_SNOOZE,  mId));
        	*/        	
        	return ;
        }      
	}     
	
	
	/**
	 * 2012.03.26 suein1209.kim
	 * do side volume button action
	 */
	private void doSideVolumeBtnBehavior(){
		final String SNOOSE = "1";
		final String STOP = "2";
		final String SILENCE = "3";
		
		if((mbPuzzle || playing) == true){
			
			if (SNOOSE.equals(sideButtons)) {
				snoozeChanged() ;
				
			} else if (STOP.equals(sideButtons)) {
				stopChanged();
				
			} else if (SILENCE.equals(sideButtons)) {
				soundAndVibratorCancel(mId);
				
			} //End Of if
		}
	} //End Of Method doSideVolumeBtnBehavior
	
    /**
     *  volume up/down => snooze or stop
     * @param keyCode int
     * @param event KeyEvent
     * @return boolean
     * @see android.view.KeyEvent$Callback#onKeyUp(int, KeyEvent)
     */
	@Override
    public boolean onKeyUp(int keyCode, KeyEvent event) { 
    	switch (keyCode) { 		
		/*[START] 2012.03.26 suein1209.kim refectory side button*/
		case KeyEvent.KEYCODE_VOLUME_UP : 
		case KeyEvent.KEYCODE_VOLUME_DOWN:
			
			/* if puzzle mode, do nothing*/
			if(mbPuzzle) return true;
			
			doSideVolumeBtnBehavior();
			return true;
		/*[END] 2012.03.26 suein1209.kim refectory side button*/
			
			case KEYCODE_3DCAMERA: 
				Log.d(TAG, "======up >> down==========");
				//[hyunjung78.park][1458] 2011.10.18 START
				if(mbPuzzle){
					return true;
				}else{
					if ("1".equals(sideButtons)) {
						snoozeChanged() ;
					} else if ("2".equals(sideButtons)) {
						stopChanged();
					}
					return true;
				}
				//[hyunjung78.park][1458] 2011.10.18 END
			case KeyEvent.KEYCODE_BACK | KeyEvent.KEYCODE_MENU | KeyEvent.KEYCODE_SEARCH:
				break;
				
			default:
				break;
    	} 
    	
    	return false; 	
    }    
    
    /**
     * Method onKeyDown.
     * @param keyCode int
     * @param event KeyEvent
     * @return boolean
     * @see android.view.KeyEvent$Callback#onKeyDown(int, KeyEvent)
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
    	switch (keyCode) { 		
			case KeyEvent.KEYCODE_VOLUME_UP :
				Log.d(TAG, "======down >> up==========");
				return true; 
			      
			case KeyEvent.KEYCODE_VOLUME_DOWN: 
				Log.d(TAG, "======down >> down==========");
				return true;
			
			default :
				break;
    	}
    	
		return false; 	
	} 
    ////////////////////////////////////////////////////////// 	
       
    /**
     *  alarm activity => snooze button click
     * @see com.lge.clock.alarmclock.StopSnoozeButton$SnoozeListener#snoozeChanged()
     */
	public void snoozeChanged() {
		Log.d(TAG, "snoozeChanged,  state = snooze  BOTH_BUTTON ");
		soundAndVibratorCancel(mId);
		Log.i(TAG, "snoozeChanged,  DIALOG_CHECKED state : " + mDIALOG_CHECKED);
		if ( mDIALOG_CHECKED )	
			mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_SNOOZE,  mId));
	}
	
	/**
     *  alarm activity => stop button click
     * @see com.lge.clock.alarmclock.StopSnoozeButton$StopListener#stopChanged()
	 */
	public void stopChanged() {
		Log.d(TAG, "stopChanged,  state = stop  BOTH_BUTTON "); //
		soundAndVibratorCancel(mId);
		
		mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_STOP,  mId));
	}
	  
    /**
     * @return true if clock is set to 24-hour mode
     */  
    private static boolean is24HourMode(final Context context) {
        return android.text.format.DateFormat.is24HourFormat(context);
    } 
    /////////////////////////////////////////////////////////////////////////
    private boolean playing	=	false ;
	// Internal messages
    private static final int KILLER 				  =		1000;
    private static final int PLAY   				  =		1001;
    private static final int ALARM_STOP 		  	  =		1002;
    private static final int ALARM_SNOOZE   	      =		1003;
    private static final int SECOND_ENDING   		  =		1004;
    private static final int CHOICE_SNOOZE            = 	1005;
    private static final int ALARM_AUTOSTOP			  = 	1006;
    //private static final int TEN_MINUTES_AUTO_FINISH  =     1006; //added by essin@lge.com 2010.11.29
    ///////////////////////////////////////////////////////////////////////
     
	private MediaPlayer mMediaPlayer;
	private Vibrator vibrator;
	/**
	 * msg.what : EVENT   msg.obj : Alarm ID
	 */
	private final Handler mSoundHandler = new Handler() {
	    public void handleMessage(Message msg) {
	    	switch (msg.what) 
	    	{
	    		case ALARM_STOP :
	    			alarmStop();
	    			break;
	    			
	    		case ALARM_SNOOZE :
	    			alarmSnooze();
	    			break;
	    		
	    		case CHOICE_SNOOZE :
//	    			alertDialog.cancel();
	    			alarmChoiceSnooze();
	    			break;
	    			
	    		case SECOND_ENDING :
	    			finish();
	    			break;
	    		
	    		case PLAY :
	    			Object aa = msg.obj;
	            	String strID = String.valueOf(aa);
	            	Log.d(TAG, "==== PLAY=====" + strID);
	            	try {
	            		soundPlay( Integer.parseInt(strID) );
	            	} catch ( NumberFormatException e ) {
	            		e.printStackTrace();
	            	}
	    			break;
	    			
	    		case ALARM_AUTOSTOP :
	    			stopFlag = "stop";
	    		case KILLER:
	            	Object aa1 = msg.obj ;
	            	String strkillID = String.valueOf(aa1);
	            	Log.d(TAG, "KILLER(Sound/Vib) =====" + strkillID);
	            	try {
	            		soundStop( Integer.parseInt(strkillID) );
	            	} catch ( NumberFormatException e ) {
	            		e.printStackTrace();
	            	}
	            	
	            	if (stopFlag != null && "stop".equals(stopFlag)) {
	            		stopFlag = "";
	            		autoAlarmClose();
	            		finish();
	            	} else {
	            		autoSnoozeGoing();
	            	}
	            	break;
	            	
	            	//added by essin@lge.com 2010.11.29
	    		//case TEN_MINUTES_AUTO_FINISH:
	    			//if(dialogSelectionYN == false) {
//	    				snoozeCancel();
	    			//}
	    		//	break;
	    			
	    		default :
	    			break;
	    	}
	    }
	};
	
	/**
     *	auto alarm Close <========
     */       
    private void autoAlarmClose() {
    	/////////////////// Snooze off -> Snooze 5 min ///////////////////////////
//    	mSnooze = 5;
//    	mSoundHandler.sendMessage(mSoundHandler.obtainMessage(CHOICE_SNOOZE,  mId));
    	
    	/* disable alarm only if it is not set to repeat */
    	/* not repeat */
        Alarms.noRepeatChecking(this, mId, false);
    	
    	/////////////////////////////////////////////////////////////////
        NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    	nm.cancel(mId); 
		///////////////////////////////////////////////////////////////////////
    	CharSequence from = null;
        // The details of our fake message
        if (mMemo == null || "".equals(mMemo.trim())) {
        	from = getText(R.string.alarm).toString();
        }
        else {
        	from = getText(R.string.alarm).toString() + "(" + mMemo + ")";
        }
        ////////////////////////////////////////////////////////////
        Intent fireAlarm = new Intent(this, ALReceiver.class);
        fireAlarm.setAction(Alarms.ALARM_STOP);
	    fireAlarm.putExtra("id", mId);
//	    fireAlarm.putExtra("memo", mMemo); 
	    //fireAlarm.putExtra("weather", mWeather);  
	    PendingIntent broadcast = PendingIntent.getBroadcast(this, mId, fireAlarm, 0);
	    
        CharSequence message = getText(R.string.sp_alarm_stop_NORMAL);
        Notification notif = new Notification(R.drawable.stat_notify_alarm, from, mTime);
      
        // Set the info for the views that show in the notification panel.
        notif.setLatestEventInfo(this, from, message, broadcast);
        notif.deleteIntent = broadcast;
        notif.flags |= Notification.FLAG_AUTO_CANCEL;
        
        if((CommonUtil.getBuildOperator() == OPERATOR.DCM 
        		|| CommonUtil.getBuildOperator() == OPERATOR.VZW)
        		&& CommonUtil.isPowerLEDSetInSettings(mResolver) == 0){
        	
        	notif.flags |= Notification.DEFAULT_LIGHTS;
        	
        }else{
        	
        	notif.flags |= Notification.FLAG_SHOW_LIGHTS;	
        	notif.defaults |= Notification.DEFAULT_LIGHTS;
        	
        } //End Of if
        
//        notif.ledARGB = 0xFF00FF00;
//        notif.ledOnMS = 500;
//        notif.ledOffMS = 500;
        nm.notify(mId,  notif);
        /////////////////////////////////////////////////////////////////
    }
     
    /**
     *	auto snooze Close <========
     */       
	private void autoSnoozeGoing() {
		
		if (mSnooze == 0) {
			mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_STOP,  mId));
			return;
		}
		NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		nm.cancel(mId);
	            	                         
		// Notify the user that the alarm has been snoozed.
		Intent cancelSnooze = new Intent(this, ALReceiver.class);
        cancelSnooze.setAction(Alarms.CANCEL_SNOOZE);
        cancelSnooze.putExtra("id", mId);
        PendingIntent broadcast = PendingIntent.getBroadcast(this, mId, cancelSnooze, 0);
              
        // The details of our fake message
        CharSequence from = null ;
        if (mMemo == null || "".equals(mMemo.trim())) {
        	from = getText(R.string.sp_snooze_ment_NORMAL).toString();
        } else {
        	//TD#15874 fixed by mo2sangbong.lee@lge.com 2011.07.25 added space Start
        	from = getText(R.string.sp_snooze_ment_NORMAL).toString() + " " + "(" + mMemo + ")";
        	//TD#15874 fixed by mo2sangbong.lee@lge.com 2011.07.25 added space End
        }
        ///////////////////////////////////////////////
        Calendar c3 = Calendar.getInstance();
        if ( mAutoSnoozeStartTime == 0L ) {
        	c3.setTimeInMillis(System.currentTimeMillis()); //added by essin@lge.com 2010.11.29
        } else {
        	c3.setTimeInMillis(mAutoSnoozeStartTime);
        }
        c3.set(Calendar.SECOND, 0);
        c3.set(Calendar.MILLISECOND, 0);  
        ////////////////////////////////////////////////
        snoozeRefreshing(c3.getTimeInMillis());
        
        if ( mSnoozeChecker ) {
	        CharSequence message = getText(R.string.alarm_ment1).toString() + " " + getNotiSnoozeTime(c3.getTimeInMillis()) ;				        
	        Notification notif = new Notification(R.drawable.stat_notify_alarm, from, 0);
	        notif.setLatestEventInfo(this, from, message,  broadcast);
	        notif.deleteIntent = broadcast;
	        notif.flags |= Notification.FLAG_AUTO_CANCEL;
	        
	        if((CommonUtil.getBuildOperator() == OPERATOR.DCM 
	        		|| CommonUtil.getBuildOperator() == OPERATOR.VZW)
	        		&& CommonUtil.isPowerLEDSetInSettings(mResolver) == 0){
	        	
	        	notif.flags |= Notification.DEFAULT_LIGHTS;
	        	
	        }else{
	        	
	        	notif.flags |= Notification.FLAG_SHOW_LIGHTS;	
	        	notif.defaults |= Notification.DEFAULT_LIGHTS;
	        	
	        } //End Of if
//	        notif.ledARGB = 0xFF00FF00;
//	        notif.ledOnMS = 500;
//	        notif.ledOffMS = 500;
	        nm.notify(mId, notif);   
               
			Resources res = getResources();  
        	CharSequence[] snooze_button_popup = res.getTextArray(R.array.sp_snooze_popup_NORMAL); 
	//		int[] timeMap = {5,10,15,20,25,30 }; 
			int[] timeMap = {5,10,15,20,25,30,60 }; //added by essin@lge.com 2010.12.20
			String showMessage	= "" ;
			for (int i=0 ; i < timeMap.length; i++) {
				if (  timeMap[i] ==  mSnooze ) {
					showMessage	=  (String)snooze_button_popup[i] ;
					break;
				}
			}
			//////////////////////////////////////////////////////////////////////////////////////
			Toast.makeText(AlarmAlert.this, showMessage,  Toast.LENGTH_SHORT).show();
			finish();   
        }
	}
	 
	/**
     *   snooze refresh
     */                       
    private void snoozeRefreshing(long itime) {
    	int autoSnoozeChecker = 0;
    	
    	int snooze_count = 0;
    	Cursor scc = null;
    	try {
    		scc = mResolver.query(ALProvider.CONTENT_CALCU_URI, null,  "aid=" + mId + " and aindex > 0", null, null);
    		if ( scc != null )
    			snooze_count = scc.getCount();
    	} catch ( Exception e) {
    		e.printStackTrace();
    	}
    	finally {
    		if ( scc != null ) 
    			scc.close();
    	}
    	
		int totalCount = 0;
		if ( snooze_count > 0 ) {
			// snooze time is unconditional delete, then snooze time set again.
			mResolver.delete(ALProvider.CONTENT_CALCU_URI, "aid = " + mId + "  and aindex > 0", null);
	    	totalCount = snooze_count;
		}else if ( snooze_count == 0 ) {
			totalCount = 5;
		}
		
    	final String[] alarmNeedColumns = { "daysofweek", "hour", "minutes" };
    	
    	int daysofweek = 0, hour = 0, minutes = 0;
    	Cursor cc = null;
    	try {
    		cc = mResolver.query(ALProvider.CONTENT_ALARMS_URI, alarmNeedColumns, "_id=" + mId, null, null );
    		if ( cc != null && cc.moveToFirst() ) {
            	do {
            		daysofweek = cc.getInt(0);
            		hour       = cc.getInt(1);
            		minutes    = cc.getInt(2);
    			} while(cc.moveToNext());
    		}
    	} catch ( Exception e ) {
    		e.printStackTrace();
    	} finally {
    		if ( cc != null )
    			cc.close();
    	}
        
        ContentValues values = null;
        Calendar c3 = Calendar.getInstance();
        c3.setTimeInMillis( itime );
        c3.set(Calendar.SECOND, 0); //added by essin@lge.com 2010.11.29
        c3.set(Calendar.MILLISECOND, 0); //added by essin@lge.com 2010.11.29
        Date dd1 = null;
        long alarm_time = c3.getTimeInMillis();

        Log.d(TAG, " ===  SnoozeButtonProcess  === START mTime =======> " + alarm_time + "  /  snooze(min) interval => " + mSnooze );   
        for ( int i = 1; i <= totalCount; i++ ) {                
        	long aa	= alarm_time + (1000 * 60 * i * mSnooze);
        	c3.setTimeInMillis( aa );       
        	dd1 = c3.getTime();        
            Log.d(TAG,  i + " th=>" + c3.getTimeInMillis() + " Time=>" + dd1.toString() );     
            Log.d(TAG,  "============================================================"  );
                                                     
            values = new ContentValues();
            values.put( "aid",    mId );
            values.put( "aindex", i );
            ////////////////////////////////////////////////
            values.put( "hour",  hour );
            values.put( "minutes", minutes );
            values.put( "daysofweek", daysofweek );
            values.put( "enabled", 1 );
            values.put( "time", c3.getTimeInMillis() );
            values.put( "status", "S" );
            if ( i != totalCount ) {
            	values.put( "stop",  "" );
            }else {
            	values.put( "stop",  "stop" );
            }
            ////////////////////////////////////////////////                      
            mResolver.insert(ALProvider.CONTENT_CALCU_URI, values);
    		autoSnoozeChecker++;
        }
        
        if ( 1 == autoSnoozeChecker ) {
        	mSnoozeChecker = false;
        	alarmStop();
        	NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
//        	nm.cancel(mId);
        	
        	Intent alarmStop = new Intent(this, ALReceiver.class);
            alarmStop.setAction(Alarms.ALARM_STOP);
            alarmStop.putExtra( "id", mId );
            PendingIntent broadcast = PendingIntent.getBroadcast(this, mId, alarmStop, 0);
        	
        	CharSequence from = null;
            if ( mMemo == null || "".equals(mMemo.trim()) ) {
            	from = getText(R.string.alarm);
            } else {
            	from = getText(R.string.alarm).toString() + "(" + mMemo + ")";
            }
            
            CharSequence message = getText(R.string.sp_alarm_stop_NORMAL);				        
            Notification notif = new Notification(R.drawable.stat_notify_alarm, from, mTime); //seungchul.kang@lge.com
            
            notif.setLatestEventInfo(this, from, message,  broadcast);
            notif.deleteIntent = broadcast;
            notif.flags |= Notification.FLAG_AUTO_CANCEL;
            
	        if((CommonUtil.getBuildOperator() == OPERATOR.DCM 
	        		|| CommonUtil.getBuildOperator() == OPERATOR.VZW)
	        		&& CommonUtil.isPowerLEDSetInSettings(mResolver) == 0){
	        	
	        	notif.flags |= Notification.DEFAULT_LIGHTS;
	        	
	        }else{
	        	
	        	notif.flags |= Notification.FLAG_SHOW_LIGHTS;	
	        	notif.defaults |= Notification.DEFAULT_LIGHTS;
	        	
	        } //End Of if
//            notif.ledARGB = 0xFF00FF00;
//            notif.ledOnMS = 500;
//            notif.ledOffMS = 500;
            nm.notify(mId, notif);
        }
        else {
        	mSnoozeChecker = true;
        }
    }
	
    // stop dialog      
    private void alarmStop() {
    	////////////////////////////////////////////////////////////////////////////
    	mResolver.delete(ALProvider.CONTENT_CALCU_URI, "aid = " + mId + " and aindex > 0", null);

    	Alarms.noRepeatChecking(this, mId, false);
           
        NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    	nm.cancel(mId);
        
    	//Toast.makeText(AlarmAlert.this, this.getText(R.string.stop_button_popup).toString(),  Toast.LENGTH_SHORT).show();
        mSoundHandler.sendMessageDelayed(mSoundHandler.obtainMessage(SECOND_ENDING, mId), 0); 
    }
    
    // snooze dialog
    private void alarmSnooze() {
    	Resources res = getResources();
		CharSequence[] snooze_button_popup = res.getTextArray(R.array.sp_snooze_popup_NORMAL);
		int[] timeMap = {5,10,15,20,25,30,60 }; //added by essin@lge.com 2010.12.20
		
		Log.v(TAG, "mSnooze : " + mSnooze);
		
		StringBuffer strMessage = new StringBuffer(CommonUtil.STR_BUF_DEF_SIZE);
		if ( mSnooze > 0 ) {
			for ( int i = 0; i < timeMap.length; i++ ) {
    			if ( timeMap[i] ==  mSnooze ) {
    				strMessage.append( snooze_button_popup[i] );
    				break;
    			}
    		}
			
			//////////////////////////////////////////////////////////////////////////////
			// DO IT UNDER
        	Log.d(TAG, "==mSnoozeButton Button click=========");
        	
        	Calendar c3 = Calendar.getInstance();
        	c3.setTimeInMillis(System.currentTimeMillis());
            c3.set(Calendar.SECOND, 0);
            c3.set(Calendar.MILLISECOND, 0);
        	snoozeTimeSetting(c3.getTimeInMillis());
        	
        	// ============  Noti clear begin===============
            NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        	nm.cancel(mId);
            //===============================================================================
        	
        	// Notify the user that the alarm has been snoozed.
            Intent cancelSnooze = new Intent(this, ALReceiver.class);
            cancelSnooze.setAction(Alarms.CANCEL_SNOOZE);
            cancelSnooze.putExtra( "id", mId );
            PendingIntent broadcast = PendingIntent.getBroadcast(this, mId, cancelSnooze, 0);
                                                              
            // The details of our fake message
            CharSequence from = null;
	        if ( mMemo == null || "".equals(mMemo.trim()) ) {
	        	from = getText(R.string.sp_snooze_ment_NORMAL);
	        } else {
	        	//TD#15874 fixed by mo2sangbong.lee@lge.com 2011.07.25 added space Start
	        	from = getText(R.string.sp_snooze_ment_NORMAL).toString() + " " + "(" + mMemo + ")";
	        	//TD#15874 fixed by mo2sangbong.lee@lge.com 2011.07.25 added space End
	        }
	        
	        CharSequence message = getText(R.string.alarm_ment1).toString() + " " + getNotiSnoozeTime( c3.getTimeInMillis() );
	        
            Notification notif = new Notification(R.drawable.stat_notify_alarm, from, 0);
            notif.setLatestEventInfo(this, from, message, broadcast);
            notif.deleteIntent = broadcast;
            notif.flags |= Notification.FLAG_AUTO_CANCEL;
            
	        if((CommonUtil.getBuildOperator() == OPERATOR.DCM 
	        		|| CommonUtil.getBuildOperator() == OPERATOR.VZW)
	        		&& CommonUtil.isPowerLEDSetInSettings(mResolver) == 0){
	        	
	        	notif.flags |= Notification.DEFAULT_LIGHTS;
	        	
	        }else{
	        	
	        	notif.flags |= Notification.FLAG_SHOW_LIGHTS;	
	        	notif.defaults |= Notification.DEFAULT_LIGHTS;
	        	
	        } //End Of if
//            notif.ledARGB = 0xFF00FF00;
//            notif.ledOnMS = 500;
//            notif.ledOffMS = 500;
            nm.notify(mId, notif);
    		///////////////////////////////////////////////////////////////////////
            Toast.makeText(AlarmAlert.this, strMessage.toString(), Toast.LENGTH_SHORT).show();
            mSoundHandler.sendMessageDelayed(mSoundHandler.obtainMessage(SECOND_ENDING, mId), 1400);
		} 
		else if (mSnooze == 0) {
			specialDialog();
		}
    }
        
    /**
     *    all snooze time is delete, then snooze set again
     */
    private void snoozeTimeSetting(long itime) {
        /////////////////////////////////////////////////////////////////////////////////////
    	// snooze time is unconditional delete, then snooze set again
    	mResolver.delete(ALProvider.CONTENT_CALCU_URI, "aid = " + mId + " and aindex > 0", null);
    	//.....
    	final String[] alarmNeedColumns = { "daysofweek", "hour", "minutes" };
    	
    	int daysofweek = 0, hour = 0, minutes = 0;
    	Cursor cc = null;
    	try {
    		cc = mResolver.query(ALProvider.CONTENT_ALARMS_URI, alarmNeedColumns, "_id=" + mId, null, null);
    		if ( cc != null && cc.moveToFirst() ) {
            	do {
            		daysofweek = cc.getInt(0);
            		hour       = cc.getInt(1);
            		minutes    = cc.getInt(2);
    			} while( cc.moveToNext() );
    		}
    	} catch ( Exception e) {
    		e.printStackTrace();
    	} finally {
    		if ( cc != null )
    			cc.close();
    	}
        
        ContentValues values = null;
        Calendar c3 = Calendar.getInstance();
        c3.setTimeInMillis( itime );
        c3.set(Calendar.SECOND, 0); //added by essin@lge.com 2010.11.29
        c3.set(Calendar.MILLISECOND, 0); //added by essin@gle.com 2010.11.29
        Date dd1 = null;
        long alarm_time = c3.getTimeInMillis();
                             
        Log.d(TAG, " ===  SnoozeButtonProcess  === START mTime =======> " + alarm_time + "  /  snooze(min) interval => " + mSnooze );
        for ( int i = 1; i <= 5; i++ ) {
        	long aa	= alarm_time + (1000 * 60 * i * mSnooze);
        	c3.setTimeInMillis( aa );
        	dd1 = c3.getTime();
            Log.d(TAG, i + " th=>" + c3.getTimeInMillis() + " Time=>" + dd1.toString() );
            Log.d(TAG, "============================================================" );
                                                     
            values = new ContentValues();
            values.put( "aid",    mId );
            values.put( "aindex", i );
            ////////////////////////////////////////////////
            values.put( "hour",       hour );
            values.put( "minutes",    minutes );
            values.put( "daysofweek", daysofweek );
            values.put( "enabled",    1 );
            values.put( "time",       c3.getTimeInMillis() );
            values.put( "status",     "S" );
            if (i != 5) {
            	values.put( "stop", "" );
            }else {
            	values.put( "stop", "stop" );
            }
            ////////////////////////////////////////////////                      
            mResolver.insert(ALProvider.CONTENT_CALCU_URI, values);
        }
    }
    
    // choice snooze logic          
    private void alarmChoiceSnooze() {
    	///////// [[changed snooze identify for dialog]] //////////////////
    	ContentValues values = new ContentValues();
    	values.put( "snooze", mSnooze );
    	getContentResolver().update(ALProvider.CONTENT_ALARMS_URI, values, "_id = " + mId, null);
    	alarmSnooze();
    }
    
    /**
     *   it canceled in snooze popup
     */
    private void snoozeCancel() {
    	//added by essin@lge.com 2010.11.29
    	dialogSelectionYN = true;
    	NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    	nm.cancel(mId);
    	/* disable alarm only if it is not set to repeat */
    	Alarms.noRepeatChecking(this, mId, false);
        
    	Log.d(TAG, "=== << you push cancel button >>============");
    	//-- start // Stop toast  ///////////////
    	mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_STOP,  mId));
    	//-- end  ///////////////////////////////////////////////////////////
    }
    
    /**
     *  it choice snooze in snooze popup
     */
    private void snoozeChoice() {
    	mDIALOG_CHECKED = true;
    	dialogSelectionYN = true; // added by essin@lge.com 2010.11.29
    	if ( mSnooze != 0 ) {
    		mSoundHandler.sendMessage( mSoundHandler.obtainMessage(CHOICE_SNOOZE,  mId) );
    	}
    } 
    
    /**
	 * in case Snooz=0, it choice snooze again in dialog box
	 */
    private boolean dialogSelectionYN = false; // added by essin@lge.com 2010.11.29
    private AlertDialog alertDialog;
    private void specialDialog() {
    	///////////////////////////////////////////////////////////////////////
    	// DO IT UNDER
    	mResolver.delete(ALProvider.CONTENT_CALCU_URI, "aid = " + mId + " and aindex > 0",  null);
    	
    	mDIALOG_CHECKED = false;
    	dialogSelectionYN = false; // added by essin@lge.com 2010.11.29
        
    	/* added by essin@lge.com 2010.11.29
    	// ============  Noti clear begin===============
        NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    	nm.cancel(mId); 
    	
    	if ("snooze".equalsIgnoreCase(mGubun)) {
            nm.cancel(mId);
		}         
        */
    	//////////////////////////////////////////////////////////////////////
		AlertDialog.Builder builder1 ;
		builder1 = new AlertDialog.Builder(this);
        builder1.setTitle(R.string.snooze_button);
        builder1.setCancelable(false);
        builder1.setNegativeButton( R.string.alert_dialog_cancel , new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface dialog, int which) {
        		mDIALOG_CHECKED = true;
//	            snoozeCancel();
	            // [mo2sangbong.lee@lge.com][22540] 2011.08.22. alarm alert does not play sound issue fix START	
	            soundPlay(mId);
	            // [mo2sangbong.lee@lge.com][22540] 2011.08.22. alarm alert does not play sound issue fix END	
	            return;
	        }
        });
        
        builder1.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if ( KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
					Log.d(TAG, "====Back Key=======>" +  event.getKeyCode() );
					alertDialog.cancel();
					mDIALOG_CHECKED = true;
					// [mo2sangbong.lee@lge.com][22540] 2011.08.22. alarm alert does not play sound issue fix START	
					soundPlay(mId);
					// [mo2sangbong.lee@lge.com][22540] 2011.08.22. alarm alert does not play sound issue fix END					
					return true;
				}
				return dispatchKeyEvent(event);
			} 
		});  
                                                                         
        builder1.setSingleChoiceItems(R.array.STR_Clock_SELECTSNOOZEKINDS_NORMAL, 0, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            	////////////////////////////////////////////////////////////////////////
                /* User clicked so do some stuff */ 
                // String[] items = getResources().getStringArray(R.array.select_snooze_items);
            	// String selected_message = "Snooze time changed to " + items[which] ;    // + "  <==> Original : " + mSnooze + " min";
            	// Toast.makeText(AlarmAlert.this, selected_message,  Toast.LENGTH_SHORT).show();
				if		(which == 0) {
					mSnooze = 0;
					// [mo2sangbong.lee@lge.com][22540] 2011.08.22. alarm alert does not play sound issue fix START	
					soundPlay(mId);
					// [mo2sangbong.lee@lge.com][22540] 2011.08.22. alarm alert does not play sound issue fix END					
				}
            	else if (which == 1)	mSnooze = 5;
				else if (which == 2)	mSnooze = 10;
				else if (which == 3)	mSnooze = 15;
				else if (which == 4)	mSnooze = 20;
				else if (which == 5)	mSnooze = 25;
				else if (which == 6)	mSnooze = 30;
				else if (which == 7)	mSnooze = 60;
            	Log.d(TAG, "==which===>" +  which );
            	alertDialog.cancel();
            	snoozeChoice();
            }
        });
     /////////////////////////////////////////////////////////////////////////////////////////////////  
        alertDialog = builder1.show();
	}      
    
    //BASICPKG_S AlarmClock [sungtan.back@lge.com 110328]
	//modify getCalendar -> getNotiSnoozeTime, call func from CommonUtil  
    private String getNotiSnoozeTime(final long time) {
    	long snoozeTime = time + (CommonUtil.SECONDS_IN_A_MINUTE * CommonUtil.ONE_SEC_WITH_MILLI * mSnooze);
    	 
    	Calendar calendar = Calendar.getInstance();
    	calendar.setTimeInMillis( snoozeTime );
    	
    	CharSequence strAlarmTime = DateFormat.format( CommonUtil.getDateFormat(this), calendar );
    	StringBuffer strResult = new StringBuffer(strAlarmTime);
    	
    	// [1] 24 MODE
    	if ( DateFormat.is24HourFormat(this) ) {
    		strResult.append(". ");
    		strResult.append(getText(R.string.sp_alarm_right_ment_NORMAL));
    	} 
    	// [2] AM/PM MODE
    	else {
    		boolean bAM = calendar.get(Calendar.AM_PM) == Calendar.AM;
    		CharSequence strAPM = getText(R.string.sp_PM_string_NORMAL);
    		if ( bAM )
    			strAPM = getText(R.string.sp_AM_string_NORMAL);
    		
    		strResult.append(' ');
			strResult.append(strAPM);
			strResult.append(". ");
			strResult.append(getText(R.string.sp_alarm_right_ment_NORMAL));
    	}
    	
    	return strResult.toString();
    }
    //BASICPKG_E
    
    private static final int LED_RGB = 0xFF00FF00;
    private static final int LED_ON_MS  = 500;
    private static final int LED_OFF_MS = 500;
    
    /**
     *   (multialarm, multisnooze checked = true) => save 
     */
    private static final String[] CALCU_COLS = { "_id",  "aid",  "time", "aindex", "status", "stop" };
    private boolean multiCheck(int mId, long mTime, boolean newIntentYN) {
    	boolean returnTag = false;
    	NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    	
    	Cursor cc = null;
    	try {
    		if (newIntentYN == true) {
        		cc = mResolver.query(Uri.parse(("content://com.lge.clock.alarmclock.ALProvider/calcus").concat("?calcuqueryType=1")), CALCU_COLS, 
    					 							"enabled = '1' and time = " + mTime + " and aid >= " + mId, null, "time, status, aid" );
        	} else {
        		cc = mResolver.query(Uri.parse(("content://com.lge.clock.alarmclock.ALProvider/calcus").concat("?calcuqueryType=1")), CALCU_COLS, 
    												 "enabled = '1' and time = " + mTime + " and aid != " + mId, null, "time, status, aid" );
        	}
        	
        	if (cc != null && cc.getCount() > 0) {//[hyunjung78.park] 2011.08.09 cursor null check
        		returnTag = true;
        	}
        	
        	Log.d(TAG, "====multiCheck==== / Id : " + mId + " time : " + mTime + " <==> " + returnTag);
        	if ( cc != null && cc.moveToFirst() ) {
        		do {
        			int snooze = 0;
    				int pk     = cc.getInt(0);
    				int aid    = cc.getInt(1);
    			    int aindex = cc.getInt(3);
    			    	         
    			    Intent intent = new Intent(this, AlarmAlert.class);
    			    intent.putExtra("id", aid);
    			    intent.putExtra("time", mTime);
    			    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
    			    intent.putExtra("multi", "yes");
    			        
    			    Log.d(TAG, " multiCheck - alarm Next ID - " + aid + "  ========================> " + aindex);
    			         
    			    if (aindex == 0) {
    			    	Log.d(TAG, "  ============= ALARM =============  " );
    			        intent.putExtra( "gubun", "alarm" );
    			        snooze = getSnoozeTime(this, aid);
    			        intent.putExtra( "snooze", snooze );
    			        if ( snooze > 0 ) {
    				       	intent.putExtra( "stop", "" );
    				    } else {
    				       	intent.putExtra( "stop", "stop" );
    				    }
    			    } else {
    			    	Log.d(TAG, "  ============= SNOOZE =============  " );
    			        String stop = cc.getString(5);
    			        intent.putExtra( "pk", pk );
    			        intent.putExtra( "gubun", "snooze" );
    			        snooze = getSnoozeTime( this, aid );
    			        intent.putExtra( "snooze",  snooze );
    			        if ( stop != null && stop.equalsIgnoreCase("stop") ) {
    				       	intent.putExtra( "stop", "stop" );
    				    } else {
    				       	intent.putExtra( "stop", "");
    				    }
    				    
    				    mResolver.delete(ALProvider.CONTENT_CALCU_URI, "_id = " + pk,  null);
    			    }
    			    
    			    intent.putExtra(AlarmMeta.COLUMNS.ALARM_MEMO,   temp_MEMO);
				    intent.putExtra(AlarmMeta.COLUMNS.ALARM_PUZZLE, temp_PUZZLE);
				    intent.putExtra(AlarmMeta.COLUMNS.ALARM_TONE,  temp_TONE);
				    intent.putExtra(AlarmMeta.COLUMNS.ALARM_VIB,  temp_VIB);
/* I3.0 Code [START] */
				    if(mIsUseVolumeControl){
				    	intent.putExtra(AlarmMeta.COLUMNS.ALARM_VOLUME, temp_ALARMVOLUME);
				    }
/* I3.0 Code [END] */
    			    
    			    // The details of our fake message
				    CharSequence from = getText(R.string.alarm);
				    /*CharSequence from = null;
				    if (temp_MEMO == null || "".equals(temp_MEMO.trim())) {
				       	from = getText(R.string.alarm).toString();
				    } else {
				       	from = getText(R.string.alarm).toString();
				       	//+ "(" + temp_MEMO + ")";
				    }*/
				                        
				    CharSequence message = getText(R.string.user_select);
				    //[mo2sangbong.lee][1596] 2011.10.26 START
				    PendingIntent contentIntent = PendingIntent.getActivity(this, aid, intent, 0);
				    //[mo2sangbong.lee][1596] 2011.10.26 END
				    Notification notif = new Notification(R.drawable.stat_notify_alarm, from, mTime);
				    // Set the info for the views that show in the notification panel.
				    notif.setLatestEventInfo(this, from, message, contentIntent);
				    
			        if((CommonUtil.getBuildOperator() == OPERATOR.DCM 
			        		|| CommonUtil.getBuildOperator() == OPERATOR.VZW)
			        		&& CommonUtil.isPowerLEDSetInSettings(mResolver) == 0){
			        	
			        	notif.flags |= Notification.DEFAULT_LIGHTS;
			        	
			        }else{
			        	
			        	notif.flags |= Notification.FLAG_SHOW_LIGHTS;	
			        	notif.defaults |= Notification.DEFAULT_LIGHTS;
			        	
			        } //End Of if
//				    notif.ledARGB  = LED_RGB;
//				    notif.ledOnMS  = LED_ON_MS;
//				    notif.ledOffMS = LED_OFF_MS;
				    nm.notify(aid, notif);
				    
    			    boolean check = false;
    			    int nSavingsSize = AlarmAlert.mSavings.size();
    		        for ( int k = 0; k < nSavingsSize; k++ ) {
    		           	Intent aa = (Intent)mSavings.elementAt(k);
    		           	if ( aid == aa.getIntExtra("id", 0) ) {
    		           		check = true;
    		           		break;
    		           	}
    		        }

    		        Log.d(TAG, "======mSavings.size() ==>" + mSavings.size());
    		        if (check == false) {
    		           	Log.d(TAG, mSavings.size() + "=======multi add OK id====>" + aid);
    		           	mSavings.add(intent);
    		        }
        		} while( cc.moveToNext() );
        	}
    	} catch ( Exception e ) {
    		e.printStackTrace();
    	} finally {
    		if ( cc != null )
    			cc.close();
    	}
        
        return returnTag;
    }
    
    private static final String[] ALARM_NEED_COLUMNS = { "_id",  "snooze",  "tone",  "vib", "memo", "puzzle" };
    
    /**
     * 	snooze (Off / 5m / 10m/ 20m / 30m/ 60m) info loading
     * @param id
     * @return 
     */
    private int getSnoozeTime(Context context, int alarmId) {
    	int snoozeSet = 0 ;
        
        ContentResolver resolver = context.getContentResolver();
        Cursor cc = null;
        try {
        	cc = resolver.query(  ALProvider.CONTENT_ALARMS_URI, mIsUseVolumeControl ? ALARM_NEED_COLUMNS_2 : ALARM_NEED_COLUMNS, "_id = " + alarmId, null, null );
        	if ( cc != null && cc.moveToFirst()) {
        		snoozeSet = cc.getInt(ALARM_NEED_COLUMNS_IDX_ALARM_SNOOZE);
				if ( !"Off".equalsIgnoreCase(cc.getString(ALARM_NEED_COLUMNS_IDX_ALARM_TONE)) ) {
					temp_TONE = cc.getString(ALARM_NEED_COLUMNS_IDX_ALARM_TONE);
				} else {
					temp_TONE = "Off";
				}
				  
				temp_VIB	= cc.getString(ALARM_NEED_COLUMNS_IDX_ALARM_VIB); 
				temp_MEMO	= cc.getString(ALARM_NEED_COLUMNS_IDX_ALARM_MEMO); 
				temp_PUZZLE = cc.getString(ALARM_NEED_COLUMNS_IDX_ALARM_PUZZLE);
/* I3.0 Code [START] */
				if(mIsUseVolumeControl)
					temp_ALARMVOLUME = cc.getString(ALARM_NEED_COLUMNS_IDX_ALARM_VOLUME);
/* I3.0 Code [END] */
    		}
        } catch( Exception e) {
        	e.printStackTrace();
        } finally {
        	if ( cc != null )
        		cc.close();
        }

        return snoozeSet;
    }
    
    private final String[] mNumDigitDrawables = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
    
    /**
     *   music play
     */
    private void alarmPlaying(int id) {
    	if ( playing ==	true ) {
    		Log.d(TAG, " == Now playing === " );
    		return;
    	}
    	
    	mSoundHandler.sendMessage( mSoundHandler.obtainMessage(PLAY, id) );
    }
    
    // Volume suggested by media team for in-call alarms.
    //private static final float IN_CALL_VOLUME = 0.125f;
    private static final long[] VIBRATE_PATTERN = new long[] { 200, 800 };
    
    private static final long[] CALLING_VIBRATE_PATTERN = new long[] { 80, 500, 80, 500 };
    
    //ANDY_PORTING LGDRM [lg-drm@lge.com 100414]
    /*
        0 : Not DRM
        1 : Rights expired or can't be used as ringtone
        2 : Valid Rights exist for ringtone
    */
    private int checkDRM(String filename) {
    	mDrmFile = false;
        mDrmSession = null;

        if (filename == null) {
            return 0;
        }

        int length = filename.length();
        if (false == (filename.regionMatches(true, length - 3, ".dm", 0, 3)
         || filename.regionMatches(true, length - 4, ".dcf", 0, 4)
         || filename.regionMatches(true, length - 4, ".odf", 0, 4)
         || filename.regionMatches(true, length - 4, ".o4a", 0, 4)
         || filename.regionMatches(true, length - 4, ".o4v", 0, 4))) {
            return 0; // Normal file
        }

        int drmType = DrmManager.isDRM(filename);
        if (drmType < Drm.CONTENT_TYPE_DM || drmType > Drm.CONTENT_TYPE_DCFV2) {
            return 0; // Normal file or not wrapped format
        }

        try {
            DrmContentSession session = DrmManager.createContentSession(filename, this);
            /*
			 * [START] 2012.02.10 suein1209.kim INTERNAL_TEST.WBT_12 - Defect #308149
			 */
			if (session == null)
				return 1; // may be default
			/*
			 * [END] 2012.02.10 suein1209.kim INTERNAL_TEST.WBT_12 - Defect #308149
			 */
            
            boolean bActionSupported = session.isActionSupported(Drm.CONTENT_ACT_RINGTONE); 
            if ( false == bActionSupported  ) {
                return 1; // Expired
            }

            int nDescInfo = session.setDecryptionInfo(false);
            if ( Drm.ERR_SUCCESS != nDescInfo ) {
                return 1; // Failed to set key info
            }

            // consume right
            session.consumeRight(session.getDrmTime(), 0);

            mDrmFile = true;
            mDrmSession = session;
            return 2;
        } catch (Exception e) {
        	e.printStackTrace();
        }

        return 1;
    }    
    private static final String[] MEDIA_EXTERNAL_COLUMNS = new String[] {//voice recode bug
   	     android.provider.BaseColumns._ID, 
   	     android.provider.MediaStore.MediaColumns.TITLE,
   	     "\"" + MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "\"",
   	     android.provider.MediaStore.Audio.AudioColumns.TITLE_KEY
	};
    /**
     * Gets a actual path for the given ringtone {@link Uri}.
     * 
     * @param ringtoneUri Ringtone uri to resolve.
     * @return A data path of given {@link Uri}.
     */
    private String getActualRingtoneUri(Context context, Uri ringtoneUri) {
    	if (context == null || ringtoneUri == null) {
    		return null;
        }
        String scheme = ringtoneUri.getScheme();
        if (scheme == null || scheme.equals("file")) {
            return ringtoneUri.getPath();
        }
        String authority = ringtoneUri.getAuthority();
        if (Settings.AUTHORITY.equals(authority)) {
            Uri uri = RingtoneManager.getActualDefaultRingtoneUri(context,
                RingtoneManager.getDefaultType(ringtoneUri));
            if (uri == null) {
                return null;
            }
            return getActualRingtoneUri(context, uri);
        } else if (MediaStore.AUTHORITY.equals(authority)) {
            Cursor cursor = null;
            String data = null;
			//voice recode bug
            Cursor cur = null;
            try {
            	String uri = mTone;
            //	Log.e(TAG, "uri ---->>>> "+uri);
            	cur = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, MEDIA_EXTERNAL_COLUMNS, "is_alarm = 1", null, "_id");

            	/*[START] 2012.02.10 suein1209.kim INTERNAL_TEST.WBT_12 - Defect #313846 */
				if (cur != null && cur.moveToFirst()) {
				/*[END] 2012.02.10 suein1209.kim INTERNAL_TEST.WBT_12 - Defect #313846 */
					Log.d(TAG, "external cur.moveToFirst()");
					
					do {
						Uri uri1 = ContentUris.withAppendedId(Uri.parse(cur.getString(2)), cur.getLong(0));
						if ( uri1.toString().equalsIgnoreCase(uri) ) {
			            	// Log.e(TAG, "ringtoneUri ---------------------- : "+ringtoneUri );
			             	cursor = context.getContentResolver().query(ringtoneUri, 
			             			new String[]{MediaStore.MediaColumns.DATA}, null, null, null);
			             	if ( cursor != null && cursor.getCount() == 1 ) {
			                     cursor.moveToFirst();
			                     data = cursor.getString(0);
			                      find_alarm_tone = true;
			                   //  Log.e(TAG, "data ---------------------- : "+data );
			                 }	
							break;
						}
					} while (cur.moveToNext());
            	}
            //voice recode bug
            } catch ( Exception e ) {
            	e.printStackTrace();
            } finally {
            	if (cur != null) {
            		cur.close();
            	}            	
            	if (cursor != null) {
                   cursor.close();
            	}
            }
            	
            return data;
        }
            
        return null;
    }
    //ANDY_END
    
    //ANDY_PORTING LGDRM [lg-drm@lge.com 100414]
    private boolean mDrmFile = false;
    private DrmContentSession mDrmSession = null; // Content session to reset keyinfo
    //ANDY_END

    private void setDataSourceFromResource(Resources resources, MediaPlayer player, int res) {
    	AssetFileDescriptor afd = null;
    	try {
    		afd = resources.openRawResourceFd(res);
    		if (afd != null)
                player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
    	} catch ( Exception e ) {
    		e.printStackTrace();
    	} finally {
    		try {
    			if ( afd != null )
    				afd.close();
    		} catch ( Exception e ) {
    			e.printStackTrace();
    		}
    	}
    }
    
    // action of alarm, vib etc.. execute function
    
	/**
	 * 2012.03.16 suein
	 * get right ring tone
	 * @param ringtone
	 * @return
	 */
	private String getRightRingtoneURI(String ringtone){
		String ret = "";
		AlarmDBQueryCondition queryCtn = CommonUtil.getBuildOperator() == OPERATOR.DCM ? AlarmDBQueryCondition.NO_CONDITION : AlarmDBQueryCondition.SET_ALARM;
		MediaInfoHolder infoHolder = CommonUtil.getFinededDefaultTone(getApplicationContext(), ringtone, queryCtn, PrefreParent.ALARM);
		
		if(infoHolder.mediaLocation == MediaLocation.NO_WHERE){
			
			/*find default ring tone*/
			MediaInfoHolder defaultHolder = getDefaultRingToneInfo(getApplicationContext(), queryCtn);
			if(defaultHolder.mediaURI != null){
				ret = defaultHolder.mediaURI.toString();
			} //End Of if
			
		}else{
			ret = infoHolder.mediaURI != null ? infoHolder.mediaURI.toString() : "";
		}//End Of if
		
		return ret;
	} //End Of Method
    
	/**
	 * 2012.03.28 suein1209.kim
	 * @throws IOException 
	 * @throws IllegalStateException 
	 * @throws SecurityException 
	 * @throws IllegalArgumentException 
	 */
	private void startAlarmWithRingtone(Context context, String mTone) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException{
		String toneUri = getRightRingtoneURI(mTone.trim());
    	String settingToneUri = toneUri;
    	if(toneUri.equals("")){
    		mTone = "Off";
    		settingToneUri = null;
    	}else{
    		mTone = settingToneUri = toneUri;
    	} //End Of if
    	
    	Settings.System.putString(mResolver, Settings.System.ALARM_ALERT, settingToneUri);
    	
    	if(mMediaPlayer == null){
    		mMediaPlayer = new MediaPlayer();
    	} //End Of if
        	
    	if(CommonUtil.getBuildOperator() == OPERATOR.DCM){
    		Object sourceObj = getCheckedRingtoneFlaginLDCM(mTone);
    		if(sourceObj instanceof String){
    			mMediaPlayer.setDataSource((String)sourceObj);
    		}else if(sourceObj instanceof Uri){
    			mMediaPlayer.setDataSource(context, (Uri)sourceObj);
    		} //End Of if
    		
    	}else{
    		mMediaPlayer.setDataSource(context, Uri.parse(mTone));
    		
    	} //End Of if
    	
        startAlarm();
	} //End Of Method startAlarmWithRingtone

	/**
	 * suein1209.kim 
	 * get checked ring tone flag in LDCM
	 * @param mTone
	 * @return
	 * @throws IOException
	 */
	private Object getCheckedRingtoneFlaginLDCM(String mTone){
		
		Object retSource = null;
		
		//LGE_S. Docomo. nexti.  dongkyu31.lee check Ringtone flag for PlayReady
//		if(mDevice.equals(mBuild.DEVICE)){
			String path = null;
			mUri = Uri.parse(mTone);
			String uriPath = mUri.toString();
                Log.d(TAG, "openMediaPlayer uriPath= " + uriPath);
                if (uriPath.startsWith("content://media")) {
                    path = getFilepathFromContentUri(mUri);
                } else if (uriPath.startsWith("content://settings")) {        	
                    path = getFilepathFromSettingsUri();
                } else {
                    path = uriPath;
                }
			if(null == mDrmManagerClient){
			mDrmManagerClient = new DrmManagerClient(this);	
			}
//			if(null == mDrmManagerClient){
//				Log.d(TAG, "~~~31> mDrmStore is null");
//			}
			boolean bCanHandle = false;
			bCanHandle = mDrmManagerClient.canHandle(path, "audio/mp4");
//			Log.d(TAG, "~~~31> nCanHandle is "+ bCanHandle);
			if(bCanHandle == true){
		//	mDrmStatus = checkRightsStatus(path, mDrmStore.Action.RINGTONE);
				try{
					int nDrmStatus;
					nDrmStatus  = mDrmManagerClient.checkRightsStatus(path, 2);		
					switch (nDrmStatus){
						case RIGHTS_EXPIRED: 
							Log.d(TAG, "mDrmStore.RightsStatus.RIGHTS_EXPIRED ");	
							//path = null; break;
						case RIGHTS_INVALID : 
							Log.d(TAG, "mDrmStore.RightsStatus.RIGHTS_INVALID");	
							path = null;
							// break;
						case RIGHTS_NOT_ACQUIRED :
							Log.d(TAG, "mDrmStore.RightsStatus.RIGHTS_NOT_ACQUIRED ");	
							path = null;
							
							retSource = DEFAULT_ALARM_PATH;
//							mMediaPlayer.setDataSource(DEFAULT_ALARM_PATH);
							break;
						case RIGHTS_VALID : 
							Log.d(TAG, "mDrmStore.RightsStatus.RIGHTS_VALID");
							
							retSource = Uri.parse(mTone);
//							mMediaPlayer.setDataSource(context, Uri.parse(mTone));

							break;
						default :
							Log.d(TAG, "default");	 
							path = null;
							retSource = DEFAULT_ALARM_PATH;
//							mMediaPlayer.setDataSource(DEFAULT_ALARM_PATH);
							break;
					} //End of switch (nDrmStatus)
				}catch(Exception ex){
					Log.d(TAG, "exception is occured" + ex);
				} //End Of try_catch
			}else{
				retSource = Uri.parse(mTone);
//				mMediaPlayer.setDataSource(context, Uri.parse(mTone));

			} //End Of if(bCanHandle == true)
			
//		}//End of if(mDevice.equals(mBuild.DEVICE))
//		else{
//			retSource = Uri.parse(mTone);
//			mMediaPlayer.setDataSource(context, Uri.parse(mTone));
//		} //End of if(mDevice.equals(mBuild.DEVICE))

		//LGE_E. Docomo. nexti. dongkyu31.lee
		
		return retSource;
	} //End Of Method getCheckedRingtoneFlaginLDCM
	
    /**
     * Method soundPlay.
     * @param id int
     */
    public void soundPlay(int id) {
    	
    	if (playing	== true) {
    		Log.d(TAG, " == Now playing === ");
    		return;
    	}

    	mSoundHandler.sendMessageDelayed(mSoundHandler.obtainMessage(KILLER, id), 1000 * 60 * 1);      
    	Log.d(TAG, "(" + id + ") === after 1 min=== play ======");
    	// TODO: Reuse mMediaPlayer instead of creating a new one and/or use
        // RingtoneManager.
    	
        mMediaPlayer = new MediaPlayer();
        //[haesun.jung] 2012.02.17 WBT Null check.
        if(mMediaPlayer == null){
        	Log.e(TAG, "Fail to create MediaPlayer !!!! ");
        	return;
        }
        
        mMediaPlayer.setOnErrorListener(new OnErrorListener() {
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Log.d(TAG, "Error occurred while playing audio.");
                mp.stop();
// I3.0 Alarm - Volume - Start
                if(mIsUseVolumeControl) {
	                if(mAudioManager != null)
	                	mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, resetVolume, 0);
	                else{
	                	mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
	                	mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, resetVolume, 0);
	                	Log.e(TAG, "mAudioManager is null ");    	
	                }
                }
// I3.0 Alarm - Volume - End
                mp.release();
                mMediaPlayer = null;
                //ANDY_PORTING LGDRM [lg-drm@lge.com 100414]
                if (mDrmFile && mDrmSession != null) {
                    // Reset used key
                	mDrmSession.setDecryptionInfo(true);
                    mDrmFile = false;
                    mDrmSession = null;
                }
                //ANDY_END
                return true;
            }
        });
           
        Context context	= this;
        int gubunJa = -1;
        if(mTone == null){
        	mTone = "Off";
        }else{
        	gubunJa = mTone.indexOf("content://");
        } //End Of if
        
        try {
  
//        	if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
        	if (CommonUtil.isCallStateIdle(mTelephonyManager, getApplicationContext()) == false) {
        		Log.d(TAG, "==== Using the in-call alarm============");
        		soundAndVibratorCancel(mId);
        		Log.d(TAG, "=== mPhoneStateListener 1===OK onCallStateChanged ====");
	            if (mSnooze > 0) {
	            	mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_SNOOZE, mId));          
	            	return;
	            } else if (mSnooze == 0) {
	            	ContentValues values = new ContentValues();
	            	mSnooze = 5;
	            	values.put("snooze", mSnooze);
	            	getContentResolver().update(ALProvider.CONTENT_ALARMS_URI, values, "_id = " + mId, null);
	            	
	            	mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_SNOOZE, mId));
	            	return ;
	            }
        	}
        	
        	// VOIP CHECK
        	SharedPreferences prefs = this.getSharedPreferences(PREFERENCES, 0);
        	String voip_state = prefs.getString("voip_state", "0");
        	if ("1".equalsIgnoreCase(voip_state)){
        		Log.d(TAG, "==== Using the VOIP in-call alarm============");
        		soundAndVibratorCancel(mId);
        		Log.d(TAG, "=== mPhoneStateListener 1===OK onCallStateChanged ====");
	            if (mSnooze > 0) {
	            	mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_SNOOZE,  mId));
	            	return;
	            } else if (mSnooze == 0) {
	            	ContentValues values = new ContentValues();
	            	mSnooze = 5;
	            	values.put("snooze", mSnooze);
	            	getContentResolver().update(ALProvider.CONTENT_ALARMS_URI, values, "_id = " + mId, null);
	            	
	            	mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_SNOOZE, mId));
	            	return;
	            }
        	}
        	else {
	        	if ( silenceModeChecking() == false ) {
                	Log.d(TAG, "======Not Using the in-call alarm============");

	        		if(( !"Off".equalsIgnoreCase(mTone) && "On".equals(mTone) ) ){
	        			startAlarmWithRingtone(context, mTone);
	        			
	        		}else if ( !"Off".equalsIgnoreCase(mTone) && gubunJa >= 0 ) {
	                    //ANDY_PORTING LGDRM [lg-drm@lge.com 100414]
	                    int status = 0;
	                    String path = null;
	                    if (Drm.LGDRM) {
	                        path = getActualRingtoneUri(this, Uri.parse(mTone));
	                        if (path != null) {
	                           status = checkDRM(path);
	                        }
	                    }
	                    
	                    if (status == 1) {
	                        // Can't be used as ringtone, ring default
	                        // TODO: Need to define default persistent alarm sound
	                        //setDataSourceFromResource(getResources(), mMediaPlayer,
	                        //        com.android.internal.R.raw.fallbackring);
	                    	legalToneSetting();
	                    } else if (status == 2) {
	                        mMediaPlayer.setDataSource(path);
	                        startAlarm();
	                    }
	                    //ANDY_END
	                    else {
	                    	
	                    	/*[START] 2012.02.03 suein1209.kimA*/
	                    	Log.i(TAG, "PLAY Ring tone : "+Uri.parse(mTone).toString());
	                    	
	                    	startAlarmWithRingtone(context, mTone);
	                    }
		            }
	        	}
	        	
	        	if ( !"Off".equalsIgnoreCase(mVib) ) {
	            	vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
					//sugeun.hwang 2012.04.13 start [6380]
//	            	vibrator.vibrate(VIBRATE_PATTERN, 0);
	            	playVibration();
					//sugeun.hwang 2012.04.13 end [6380]
	            }
        	}
        } catch (Exception ex) {  
        	ex.printStackTrace();
        	Log.v(TAG, "Using the fallback ringtone");
	        // The alert may be on the sd card which could be busy right now.
	        // Use the fallback ringtone.
	        try {
	            // Must reset the media player to clear the error state.
	        	if (mMediaPlayer != null) {
	        		mMediaPlayer.reset();
	        	}
	        	gubunJa = mTone.indexOf("content://");
	        	//mMediaPlayer.setVolume(IN_CALL_VOLUME, IN_CALL_VOLUME);
	        	playing	= true;
	            	         
	        	if (silenceModeChecking() == false) {
			    	if ( !"Off".equalsIgnoreCase(mTone) && gubunJa >= 0 ) {
			    		try {
			    			mMediaPlayer.setDataSource(context, Uri.parse(mTone));
				            startAlarm();
			        	} catch(Exception e) {
			        		e.printStackTrace();
			        		legalToneSetting();
			        	}
			    	}
		        }
		        	
	        	if ( !"Off".equalsIgnoreCase(mVib) ) {
	            	vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
	                //sugeun.hwang 2012.04.13 start [6380]
//	                vibrator.vibrate(VIBRATE_PATTERN, 0);
	            	playVibration();
					//sugeun.hwang 2012.04.13 end [6380]
	        	}
	        } catch (Exception ex2) {
	        	// At this point we just don't play anything.
	            android.util.Log.d(TAG, "Failed to play fallback ringtone", ex2);
	        } finally {
	        	playing	= true;
	        }
        } finally {
        	playing	= true;
        }
    }                                                   
                             
    private static final String[] INTERNAL_COLUMNS = new String[] {
			android.provider.BaseColumns._ID,
			android.provider.MediaStore.MediaColumns.TITLE,
		    "\"" + MediaStore.Audio.Media.INTERNAL_CONTENT_URI + "\"",
		    android.provider.MediaStore.Audio.AudioColumns.TITLE_KEY
	};
    
    private void legalToneSetting() {
    	Log.d(TAG, "===legalToneSetting====");
    	
    	Uri alert = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
	    if (alert == null) {
	    	mTone = "Off";
        	Settings.System.putString(mResolver, Settings.System.ALARM_ALERT, null);  
        	      
        	ContentValues values = new ContentValues(1);
        	values.put("tone", "Off");
        	mResolver.update(ALProvider.CONTENT_ALARMS_URI, values, "_id=" + mId , null);
        	return;
	    } else {
            try {
                Log.d(TAG, "===alert != null try ====");
                mMediaPlayer.setDataSource(this, alert);
                startAlarm();
                return;
            } catch(Exception e) {
            	e.printStackTrace();
            	
    	    	int i = 1;
                boolean tag = false;
                Log.d(TAG, "===alert != null ====");
	            String defaulttone = "";

	            Cursor cur = null;
	            try {
	            	cur = mResolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, INTERNAL_COLUMNS,
	               			"is_alarm = 1", null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
	            	
	            	if ( cur != null && cur.moveToFirst()) {
		    	 		do {
		    	 			// Get the field values     
		    	            Uri uri1 = ContentUris.withAppendedId(Uri.parse(cur.getString(2)), cur.getLong(0));
		    	            if ( uri1.toString().equalsIgnoreCase(alert.toString()) ) {
		    	            	Settings.System.putString(mResolver, Settings.System.ALARM_ALERT, uri1.toString());
		    	            	
		    	            	mTone =	uri1.toString();
		    	             	ContentValues values = new ContentValues(1);
		    	             	values.put("tone", uri1.toString());
		    	             	mResolver.update(ALProvider.CONTENT_ALARMS_URI, values, "_id = " + mId , null);
		    	             	 
		    	             	tag = true;
			    	            break;
		    	            }
		    	              
		    	            if (i == 4) {
		    	            	defaulttone = uri1.toString();
		    	            }
		    	            i++;
		    	 		} while ( cur.moveToNext() );
		    	 	}
	            } catch ( Exception ex ) {
	            	ex.printStackTrace();
	            } finally {
	            	if ( cur != null )
	            		cur.close();
	            }
	            
	    	 	if (tag == false) { 
	    	 		Settings.System.putString(mResolver, Settings.System.ALARM_ALERT, defaulttone ); 
	    	 		 
	    	 		mTone =	defaulttone;
	             	ContentValues values = new ContentValues(1);
	             	values.put("tone", defaulttone );
	             	mResolver.update(ALProvider.CONTENT_ALARMS_URI, values, "_id = " + mId , null);
		    	 }
            }
	    }
	    
	    try {
	    	mMediaPlayer.setDataSource(this, Uri.parse(mTone));
			startAlarm();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }     
    
    // Do the common stuff when starting the alarm.
    // alarm play
	private void startAlarm() throws java.io.IOException,
			IllegalArgumentException, IllegalStateException {
		// BT call effect
		// AudioManager audioManager =
		// (AudioManager)getSystemService(Context.AUDIO_SERVICE);
		// if( audioManager.getMode() == MODE_IN_CALL &&
		// (audioManager.isBluetoothA2dpOn() == true ||
		// audioManager.isBluetoothScoOn() == true) )
		// {
		// hjcheong@lge.com block comment
		// audioManager.changeModemAudioPath(5);
		// hjcheong@lge.com block comment
		// }

		// 20120420 lu.dai@lge.com change for U0 TD3562[start]
		mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);

		if (mIsUseVolumeControl) {
			// sugeun.hwang 2012.05.08 [7050] start
			if (sound_id == sound_id_check) {
				mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM,
						Integer.parseInt(mAlarmVolume), 0);
				// Log.d(TAG,"Integer.parseInt(mAlarmVolume) : "+Integer.parseInt(mAlarmVolume));
			}
			// sugeun.hwang 2012.05.08 [7050] end
		}
		try {
			mMediaPlayer.setLooping(true);
			mMediaPlayer.prepare();
		} catch (Exception ex) {
			mMediaPlayer.release();
			mMediaPlayer = null;
			mMediaPlayer = new MediaPlayer();

			mMediaPlayer.setDataSource("/system/media/audio/alarms/"
					+ SystemProperties.get("ro.config.alarm_alert"));
			mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
			mMediaPlayer.setLooping(true);
			mMediaPlayer.prepare();
		}
		mMediaPlayer.start();
		// 20120420 lu.dai@lge.com change for U0 TD3562[end]
	}
    
    // kill message send and music/snooze cancel
    //=====================================================
    /**
     * Method soundCancel.
     * @param id int
     */
    public void soundAndVibratorCancel(int id) {
        
    	playing	= false;
        mSoundHandler.removeMessages(KILLER, id); 
    	
    	/*cancel sound*/
        soundCancel(id);
    	
        /*cancel vibrator*/
        vibratorCancel(mVib);
        
    } //End of Method soundAndVibratorCancel
    
    /**
     * suein1209.kim
     * sound cancel
     * @param id
     */
    private void soundCancel(int id){
    	
    	Log.d(TAG, "soundCancel ID : "+id);
    	sound_id = id; //sugeun.hwang 2012.05.08 [7050] 
		try {
			if (mMediaPlayer != null) {
				// if ( mMediaPlayer.isPlaying() )//[hyunjung78.park] 2011.10.24
				// https://medic.lge.com/issues/1518
				mMediaPlayer.stop();
				Log.d(TAG, "mMediaPlayer.stop()");
/* I3.0 Code [START] */
				if(mIsUseVolumeControl)
					mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, resetVolume, 0);
/* I3.0 Code [END] */
				mMediaPlayer.release();
				mMediaPlayer = null;
			} // End Of if

		} catch (Exception e) {
			Log.e(TAG, "Exception : AlarmAlert -> soundAndVibratorCancel : "
					+ e.getMessage());
		} // End of method try
        
		// ANDY_PORTING LGDRM [lg-drm@lge.com 100414]
		if (mDrmFile && mDrmSession != null) {
			// Reset used key
			try {
				mDrmSession.setDecryptionInfo(true);
			} catch (Exception e) {
				Log.e(TAG, "" + e.getMessage());
			}
			mDrmFile = false;
			mDrmSession = null;
		}
		// ANDY_END
        
    } //End Of Method soundCancel
    
    /**
     * suein1209.kim
     * cancel vibrator 
     * @param vib
     */
    private void vibratorCancel(String vib){
    	if (!"Off".equalsIgnoreCase(vib)) {
    		
    		Log.d(TAG, "Vibrator cancel : "+vib);
    		
            if (vibrator != null)
                vibrator.cancel();
        } //End of if
    } //End of Method vibratorCancel
	    
    /**
     * 		music/snooze cancel
    
     * @param id int
     */
    public void soundStop(int id) {
    	playing	= false;
        Log.d(TAG, "(" + id + ") === SoundStop =============");
        if (mMediaPlayer != null) {
        	mMediaPlayer.stop();
        	Log.i(TAG, "MediaPlayer stop()");
/* I3.0 Code [START] */
        	if(mIsUseVolumeControl)
        		mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, resetVolume, 0);
/* I3.0 Code [END] */
            mMediaPlayer.release();
            mMediaPlayer = null;
            //ANDY_PORTING LGDRM [lg-drm@lge.com 100414]
            if (mDrmFile && mDrmSession != null) {
            	try {
            		// Reset used key
                    mDrmSession.setDecryptionInfo(true);
                    mDrmFile = false;
                    mDrmSession = null;
            	} catch ( Exception e ) {
            		e.printStackTrace();
            	}
            }
            //ANDY_END            
        }
         
        if (!"Off".equalsIgnoreCase(mVib)) {
        	if (vibrator != null)
        		vibrator.cancel();
        }
    }                
                                                                         
    /**
     *    silent check
     * @return
     */
    private boolean silenceModeChecking() {
		boolean bResult = false;
		Log.d(TAG, "silenceModeChecking()");    
		int getRingerMode = 0;
		final String modeRinger = "mode_ringer";
		  
		ContentResolver mContentResolver = getContentResolver();
		if( mAudioManager == null ) {
			mAudioManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
			getRingerMode = android.provider.Settings.System.getInt(mContentResolver, modeRinger, AudioManager.RINGER_MODE_NORMAL);
		}
		else {
			getRingerMode = mAudioManager.getRingerMode();
		}
		 
		String setSoundButton = "";
		switch( getRingerMode )
		{
			case RINGER_MODE_NORMAL:
				setSoundButton = "ON";
				//mSoundImgButton.setImageResource(R.drawable.expand_btn_sound_on);
				break;
			case RINGER_MODE_SILENT:
			case RINGER_MODE_VIBRATE:
				Log.d(TAG, "setSoundButton: Sound Silent");
				//mSoundImgButton.setImageResource(R.drawable.expand_btn_sound_off);
				setSoundButton = "Silent";
				break;
			default :
				break;
		}
		      
//        SharedPreferences prefs = this.getSharedPreferences(PREFERENCES, 0);
//        20100824_mhkwon_TD6879_Play_Sound_in_silent_mode [[ 
//        boolean silenceYN = prefs.getBoolean("alarm_in_silent_mode", false);
         
        final int silentModeStreams = Settings.System.getInt(getContentResolver(),
        			Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
//20100824_mhkwon_TD6879_Play_Sound_in_silent_mode ]]
       
        boolean silenceYN = false;
       
        if( (silentModeStreams & SettingsActivity.ALARM_STREAM_TYPE_BIT) == 0 )
        	silenceYN = true;
       
        Log.d(TAG,"===setSoundButton===" + setSoundButton + "==silenceYN===" + silenceYN);
                  
	    if ("Silent".equalsIgnoreCase(setSoundButton) &&  silenceYN == false) {
	    	Log.d(TAG, "==========(Silence mode even if Alarm fire)================");
	    	bResult = true;
	    }
    	
	    return bResult;
	}
    //////////Music play End ///////////
    
	/**
	 * Method finish.
	 */
	@Override
	public void finish() {
		super.finish();
		Log.d(TAG, "finish");
	}
	
	//BASICPKG_S AlarmClock [sungtan.back@lge.com 110311] support weather landscapde mode 
	/**
	 * Method onConfigurationChanged.
	 * @param newConfig Configuration
	 * @see android.content.ComponentCallbacks#onConfigurationChanged(Configuration)
	 */
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		if ( !mbPuzzle ) {
			updateLayout();
		}
		
		super.onConfigurationChanged(newConfig);
	}
	//BASICPKG_E AlarmClock
 	
 	private String m1Format;
 	 final static String M24_Check = "kk:mm";   
 	final static String M12_check = "h:mm";
 	
 	private String getCallingCalendarNow(long time) {
 		
// 		mFormat = is24HourMode(this) ? M24 : M12;
// 		
 		boolean is24HourFormat = DateFormat.is24HourFormat(this) ;
 		
    	Calendar aa = Calendar.getInstance( );  
    	aa.setTimeInMillis( time );
  		aa.set(Calendar.SECOND, 0);
        aa.set(Calendar.MILLISECOND, 0);  
    	       
        // [1] 24 MODE
    	if (setDateFormat() == true) {
	    	
	    	CharSequence alarmtime = DateFormat.format(m1Format, aa);
	    	return (alarmtime.toString() + ". " + getText(R.string.sp_alarm_right_ment_NORMAL).toString());
	        
	     // [2] AM/PM MODE
    	}else {
    		CharSequence alarmtime = DateFormat.format(m1Format, aa);
	        boolean APM_judge = aa.get(Calendar.AM_PM) == 0;
	        
	        if (APM_judge == true) {
	        	return (alarmtime.toString() + " AM");
	        }else {
	        	return (alarmtime.toString() + " PM");
	        }
    	}
    }
 	
 	private static boolean get24HourMode(final Context context) {
        return android.text.format.DateFormat.is24HourFormat(context);
    }
 	
 	private boolean setDateFormat() {
    	if (get24HourMode(this) == true) {
    		m1Format = M24_Check;
    		return true;
    	}    	
    	m1Format = M12_check;
    	return false;
    }
 	
 	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		Log.i(TAG, "onWindowFocusChanged " + isFinishing());

		if(isFinishing())
			return;
		if(mPouch){
			mAlarmIcon.setImageResource(R.drawable.alarm_alert_pouch_animation);
			mAnimation = (AnimationDrawable)mAlarmIcon.getDrawable();
			mAnimation.stop();
			mAnimation.start();
		}else{
			if(!mbPuzzle){
			mAlarmIcon.setImageResource(R.drawable.alarm_alert_animation);
			mAnimation = (AnimationDrawable)mAlarmIcon.getDrawable();
			if(isUseScraps()){
				mAnimation.start();
			}else{
				mAnimation.stop();
				mAnimation.start();
			}
		}}
	}
 	
 	public boolean isUseScraps(){
 		PackageManager pm = getPackageManager();
 		String scarpPacakgeName = "com.lge.scraps";
 		ApplicationInfo ai = null;
 		try{
 			ai = pm.getApplicationInfo(scarpPacakgeName, PackageManager.GET_META_DATA);
 	 		if(ai.packageName.equals("com.lge.scraps")){
 	 	 		return true;	
 	 		}else{
 	 			return false;
 	 		}
 		}catch(NameNotFoundException e){
 			Log.e(TAG, "AlarmAlert -> isUseScraps() -> NameNotFoundException : "+e.getMessage());
 		}catch(NullPointerException e){
 			Log.e(TAG, "AlarmAlert -> isUseScraps() -> NullPointerException : "+e.getMessage());
 		}
 		return false;
 	}
 	
 	public static final void cleanupView(View view) { 
		Log.i(TAG, "cleanupView"); 		
 		if(view instanceof ImageView) { 
            ImageView iv = (ImageView)view; 
            iv.setImageDrawable(null); 
        }
	}

 	/**
 	 * suein1209.kim
 	 * orientatation value state
 	 */
    private int mOrientationState = 0x00;
 	
    /**
     * suein1209.kim
     * calulcate orientation value
     * @param event
     * @return
     */
    private int getCalOrientationValue(SensorEvent event) {
        if (mOrientationState == 0x00)
        {
            if (Math.abs(event.values[0]) > Math.abs(event.values[1]) &&
                Math.abs(event.values[0]) > Math.abs(event.values[2])) {
                if (event.values[0] >= 0.0f)
                    mOrientationState = 0x01; // X Up
                else
                    mOrientationState = 0x02; // X Down
            } else if (Math.abs(event.values[1]) > Math.abs(event.values[0]) &&
                Math.abs(event.values[1]) > Math.abs(event.values[2])) {
                if (event.values[1] >= 0.0f)
                    mOrientationState = 0x04; // Y Up
                else
                    mOrientationState = 0x08; // Y Down
            } else if (Math.abs(event.values[2]) > Math.abs(event.values[0]) &&
                Math.abs(event.values[2]) > Math.abs(event.values[1])) {
                if (event.values[2] >= 0.0f)
                    mOrientationState = 0x10; // Z Up
                else
                    mOrientationState = 0x20; // Z Down
            }

            return 0x00;
            
        }else{
            int value = 0x00;
            float test = SensorManager.STANDARD_GRAVITY - 1.0f;

            if (event.values[0] >= test)
                value = 0x01; // X Up
            else if (event.values[0] <= -test)
                value = 0x02; // X Down
            else if (event.values[1] >= test)
                value = 0x04; // Y Up
            else if (event.values[1] <= -test)
                value = 0x08; // Y Down
            else if (event.values[2] >= test)
                value = 0x10; // Z Up
            else if (event.values[2] <= -test)
                value = 0x20; // Z Down

            if (value != 0x00 && value != mOrientationState) {
                mOrientationState = value;
                return value;
            } else
                return 0x00;
        }
    } //End of Method calOrientationValue
 	
    /**
     * facing sensor listener 
     * @author suein1209.kim
     */
	class SensorEventListenerImpl implements SensorEventListener {		

		public void onSensorChanged(SensorEvent event) {
			
			if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
	            int orientationValue = getCalOrientationValue(event);
	            if (orientationValue == 0x20){ 
	            	
	                Log.i(TAG, "AlarmAlert Activity Facing motion");
	                /* stop the noise!! */
					soundAndVibratorCancel(mId);
					
					/* do snooze or stop action and set the flag */
					doAlarmSnoozeOrStop();
	            } //End of if
	        } //End Of if 
			
		} //End of method onSensorChanged
		
		/**
		 * suein1209.kim
		 * 
		 * do snooze or stop action and set the flag
		 */
		private void doAlarmSnoozeOrStop() {
			if (AlarmClockActivity.mSensor) {
			    if (mSnooze > 0) {
			        mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_SNOOZE, mId));
			        AlarmClockActivity.mSensor = false;

			    } else if (mSnooze == 0) {
			        mSoundHandler.sendMessage(mSoundHandler.obtainMessage(ALARM_STOP, mId));
			        AlarmClockActivity.mSensor = false;
			        
			    } //End of if (mSnooze > 0)
			    
			} //End Of ifif (AlarmClockActivity.mSensor)
			
		} //End Of Method doAlarmSnoozeOrStop
		
		public void onAccuracyChanged(Sensor arg0, int arg1) {}
	} //End Of class SensorEventListenerImpl
 	
	// [suhyun99.kim][1433] 2011.10.13. START
	private OnAudioFocusChangeListener mAudioFocusListener = new OnAudioFocusChangeListener() {
	        public void onAudioFocusChange(int focusChange) {
	            // AudioFocus is a new feature: focus updates are made verbose on purpose
	            switch (focusChange) {
	                case AudioManager.AUDIOFOCUS_LOSS:
	                    Log.d(TAG, "Alarm AudioFocus: received AUDIOFOCUS_LOSS");
	                    break;
	                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
	                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
	                    Log.d(TAG, "Alarm AudioFocus: received AUDIOFOCUS_LOSS_TRANSIENT");
	                    break;
	                case AudioManager.AUDIOFOCUS_GAIN:
	                    Log.d(TAG, "Alarm AudioFocus: received AUDIOFOCUS_GAIN");
	                    break;
	                default:
	                    Log.e(TAG, "Alarm Unknown audio focus change code");
	            }
	        }
    	};
    	
	// sugeun.hwang 2012.04.13 start [6380]
	private int getVibrateType() {
		final int type = Settings.System.getInt(getContentResolver(),DISTINCTIVE_VIBRATION_ALARM, DEFAULT_VALUE);
		Log.i(TAG, "type : " + type);

		return type - 1;// setting app array 1,2,3,4 - alarm app array 0,1,2,3
						// so -1
	}

	private void playVibration() {

		if (CommonUtil.isSprintOperator()){
			int type = getVibrateType();
			long[] pattern = vib_patern[type];
			vibrator.vibrate(pattern, 0);
		} else {
			vibrator.vibrate(VIBRATE_PATTERN, 0);
		}
	}
	// sugeun.hwang 2012.04.13 end [6380]
    	
	// [suhyun99.kim][1433] 2011.10.13. END
    	
    	//LGE_S. Docomo. nexti. dongkyu31.lee
    	/** @hide 
    	    * Change the Method to get file path.. porting from B/Justin
    	    */
    	    private String getFilepathFromContentUri(Uri uri)
    	    {			
    	        String filepath = null;
    	        Cursor c = null;
    	        IContentProvider testProvider = null;

    	        try {
    	            ContentResolver resolver = this.getContentResolver();
    	            testProvider = resolver.acquireProvider(uri);
    	            
    	            if(testProvider != null)
    	            	c = testProvider.query(uri, new String[]{"_data"}, null, null, null);
    	        }
    	        catch (RemoteException e)
    	        {
    	            Log.e(TAG, "getFilepathFromContentUri... error!! ");
    	        }

    	        int count = (c != null) ? c.getCount() : 0;
    	        if (count > 0) {
    	            if (c == null) return null;
    	            c.moveToFirst();
    	            int i = c.getColumnIndex("_data");
    	            filepath = (i >= 0 ? c.getString(i) : null);
    	        }

    	        if (c != null) {
    	            c.close();
    	        }
    	        //Log.e(TAG, "getFilepathFromContentUri  filepath = " + filepath);
    	        if (filepath == null) {
    	            return null;
    	        }
    	        //Log.e(TAG, "getFilepathFromContentUri  result = " + uri);
    	        //Log.e(TAG, "getFilepathFromContentUri Media _data result = " + filepath);
    	        return filepath;
    	    }	
    	    /** @hide 
    	    * Change the Method to get file path.. porting from B/Justin
    	    */
    	    private String getFilepathFromSettingsUri()
    	    {		
    	        String filepath = null;
    	        Cursor c = null;
    	        IContentProvider testProvider = null;
    	        Uri contentUri = null;

    		Log.d(TAG, "~~~31> mUri is " + mUri);
    	        try {
    	            ContentResolver resolver = this.getContentResolver();
    	            testProvider = resolver.acquireProvider(mUri);
    	            if(testProvider!= null)
    	            	c = testProvider.query(mUri, new String[]{"value"}, null, null, null); 
    	        }
    	        catch (RemoteException e) 
    	        {			
    		    Log.d(TAG, "~~~31> RemoteException is occured." + e);
    	        }

    	        int count = (c != null) ? c.getCount() : 0;
    	        if (count > 0) {
    	            if (c == null) return null;
    	            c.moveToFirst();
    	            int i = c.getColumnIndex("value");
    	            filepath = (i >= 0 ? c.getString(i) : null);
    	        }

    	        if (c != null) {
    	            c.close();
    	        }
    	        //Log.e(TAG, "getFilepathFromSettingsUri Settings value 1result = " + filepath);
    	        if (filepath == null) {
    	            return DEFAULT_ALARM_PATH;
    	        }
    	        //Log.e(TAG, "getFilepathFromSettingsUri  result = " + mUri);
    	        //Log.e(TAG, "getFilepathFromSettingsUri Settings value 2result = " + filepath);

    	        if (filepath.startsWith("content://media") == false )
    	        {
    	            return null;			
    	        }

    	        contentUri = Uri.parse(filepath);
    	        if(contentUri == null)
    	        {
    	            return null;
    	        }

    	        return getFilepathFromContentUri(contentUri);
    	    }
    	//LGE_E. Docomo. nexti. dongkyu31.lee

}
